git
/
strbuf.c
1084 строки · 23.4 Кб
1#include "git-compat-util.h"2#include "gettext.h"3#include "hex-ll.h"4#include "strbuf.h"5#include "string-list.h"6#include "utf8.h"7#include "date.h"8
9int starts_with(const char *str, const char *prefix)10{
11for (; ; str++, prefix++)12if (!*prefix)13return 1;14else if (*str != *prefix)15return 0;16}
17
18int istarts_with(const char *str, const char *prefix)19{
20for (; ; str++, prefix++)21if (!*prefix)22return 1;23else if (tolower(*str) != tolower(*prefix))24return 0;25}
26
27int starts_with_mem(const char *str, size_t len, const char *prefix)28{
29const char *end = str + len;30for (; ; str++, prefix++) {31if (!*prefix)32return 1;33else if (str == end || *str != *prefix)34return 0;35}36}
37
38int skip_to_optional_arg_default(const char *str, const char *prefix,39const char **arg, const char *def)40{
41const char *p;42
43if (!skip_prefix(str, prefix, &p))44return 0;45
46if (!*p) {47if (arg)48*arg = def;49return 1;50}51
52if (*p != '=')53return 0;54
55if (arg)56*arg = p + 1;57return 1;58}
59
60/*
61* Used as the default ->buf value, so that people can always assume
62* buf is non NULL and ->buf is NUL terminated even for a freshly
63* initialized strbuf.
64*/
65char strbuf_slopbuf[1];66
67void strbuf_init(struct strbuf *sb, size_t hint)68{
69struct strbuf blank = STRBUF_INIT;70memcpy(sb, &blank, sizeof(*sb));71if (hint)72strbuf_grow(sb, hint);73}
74
75void strbuf_release(struct strbuf *sb)76{
77if (sb->alloc) {78free(sb->buf);79strbuf_init(sb, 0);80}81}
82
83char *strbuf_detach(struct strbuf *sb, size_t *sz)84{
85char *res;86strbuf_grow(sb, 0);87res = sb->buf;88if (sz)89*sz = sb->len;90strbuf_init(sb, 0);91return res;92}
93
94void strbuf_attach(struct strbuf *sb, void *buf, size_t len, size_t alloc)95{
96strbuf_release(sb);97sb->buf = buf;98sb->len = len;99sb->alloc = alloc;100strbuf_grow(sb, 0);101sb->buf[sb->len] = '\0';102}
103
104void strbuf_grow(struct strbuf *sb, size_t extra)105{
106int new_buf = !sb->alloc;107if (unsigned_add_overflows(extra, 1) ||108unsigned_add_overflows(sb->len, extra + 1))109die("you want to use way too much memory");110if (new_buf)111sb->buf = NULL;112ALLOC_GROW(sb->buf, sb->len + extra + 1, sb->alloc);113if (new_buf)114sb->buf[0] = '\0';115}
116
117void strbuf_trim(struct strbuf *sb)118{
119strbuf_rtrim(sb);120strbuf_ltrim(sb);121}
122
123void strbuf_rtrim(struct strbuf *sb)124{
125while (sb->len > 0 && isspace((unsigned char)sb->buf[sb->len - 1]))126sb->len--;127sb->buf[sb->len] = '\0';128}
129
130void strbuf_trim_trailing_dir_sep(struct strbuf *sb)131{
132while (sb->len > 0 && is_dir_sep((unsigned char)sb->buf[sb->len - 1]))133sb->len--;134sb->buf[sb->len] = '\0';135}
136
137void strbuf_trim_trailing_newline(struct strbuf *sb)138{
139if (sb->len > 0 && sb->buf[sb->len - 1] == '\n') {140if (--sb->len > 0 && sb->buf[sb->len - 1] == '\r')141--sb->len;142sb->buf[sb->len] = '\0';143}144}
145
146void strbuf_ltrim(struct strbuf *sb)147{
148char *b = sb->buf;149while (sb->len > 0 && isspace(*b)) {150b++;151sb->len--;152}153memmove(sb->buf, b, sb->len);154sb->buf[sb->len] = '\0';155}
156
157int strbuf_reencode(struct strbuf *sb, const char *from, const char *to)158{
159char *out;160size_t len;161
162if (same_encoding(from, to))163return 0;164
165out = reencode_string_len(sb->buf, sb->len, to, from, &len);166if (!out)167return -1;168
169strbuf_attach(sb, out, len, len);170return 0;171}
172
173void strbuf_tolower(struct strbuf *sb)174{
175char *p = sb->buf, *end = sb->buf + sb->len;176for (; p < end; p++)177*p = tolower(*p);178}
179
180struct strbuf **strbuf_split_buf(const char *str, size_t slen,181int terminator, int max)182{
183struct strbuf **ret = NULL;184size_t nr = 0, alloc = 0;185struct strbuf *t;186
187while (slen) {188int len = slen;189if (max <= 0 || nr + 1 < max) {190const char *end = memchr(str, terminator, slen);191if (end)192len = end - str + 1;193}194t = xmalloc(sizeof(struct strbuf));195strbuf_init(t, len);196strbuf_add(t, str, len);197ALLOC_GROW(ret, nr + 2, alloc);198ret[nr++] = t;199str += len;200slen -= len;201}202ALLOC_GROW(ret, nr + 1, alloc); /* In case string was empty */203ret[nr] = NULL;204return ret;205}
206
207void strbuf_add_separated_string_list(struct strbuf *str,208const char *sep,209struct string_list *slist)210{
211struct string_list_item *item;212int sep_needed = 0;213
214for_each_string_list_item(item, slist) {215if (sep_needed)216strbuf_addstr(str, sep);217strbuf_addstr(str, item->string);218sep_needed = 1;219}220}
221
222void strbuf_list_free(struct strbuf **sbs)223{
224struct strbuf **s = sbs;225
226if (!s)227return;228while (*s) {229strbuf_release(*s);230free(*s++);231}232free(sbs);233}
234
235int strbuf_cmp(const struct strbuf *a, const struct strbuf *b)236{
237size_t len = a->len < b->len ? a->len: b->len;238int cmp = memcmp(a->buf, b->buf, len);239if (cmp)240return cmp;241return a->len < b->len ? -1: a->len != b->len;242}
243
244void strbuf_splice(struct strbuf *sb, size_t pos, size_t len,245const void *data, size_t dlen)246{
247if (unsigned_add_overflows(pos, len))248die("you want to use way too much memory");249if (pos > sb->len)250die("`pos' is too far after the end of the buffer");251if (pos + len > sb->len)252die("`pos + len' is too far after the end of the buffer");253
254if (dlen >= len)255strbuf_grow(sb, dlen - len);256memmove(sb->buf + pos + dlen,257sb->buf + pos + len,258sb->len - pos - len);259memcpy(sb->buf + pos, data, dlen);260strbuf_setlen(sb, sb->len + dlen - len);261}
262
263void strbuf_insert(struct strbuf *sb, size_t pos, const void *data, size_t len)264{
265strbuf_splice(sb, pos, 0, data, len);266}
267
268void strbuf_vinsertf(struct strbuf *sb, size_t pos, const char *fmt, va_list ap)269{
270int len, len2;271char save;272va_list cp;273
274if (pos > sb->len)275die("`pos' is too far after the end of the buffer");276va_copy(cp, ap);277len = vsnprintf(sb->buf + sb->len, 0, fmt, cp);278va_end(cp);279if (len < 0)280die(_("unable to format message: %s"), fmt);281if (!len)282return; /* nothing to do */283if (unsigned_add_overflows(sb->len, len))284die("you want to use way too much memory");285strbuf_grow(sb, len);286memmove(sb->buf + pos + len, sb->buf + pos, sb->len - pos);287/* vsnprintf() will append a NUL, overwriting one of our characters */288save = sb->buf[pos + len];289len2 = vsnprintf(sb->buf + pos, len + 1, fmt, ap);290sb->buf[pos + len] = save;291if (len2 != len)292BUG("your vsnprintf is broken (returns inconsistent lengths)");293strbuf_setlen(sb, sb->len + len);294}
295
296void strbuf_insertf(struct strbuf *sb, size_t pos, const char *fmt, ...)297{
298va_list ap;299va_start(ap, fmt);300strbuf_vinsertf(sb, pos, fmt, ap);301va_end(ap);302}
303
304void strbuf_remove(struct strbuf *sb, size_t pos, size_t len)305{
306strbuf_splice(sb, pos, len, "", 0);307}
308
309void strbuf_add(struct strbuf *sb, const void *data, size_t len)310{
311strbuf_grow(sb, len);312memcpy(sb->buf + sb->len, data, len);313strbuf_setlen(sb, sb->len + len);314}
315
316void strbuf_addstrings(struct strbuf *sb, const char *s, size_t n)317{
318size_t len = strlen(s);319
320strbuf_grow(sb, st_mult(len, n));321for (size_t i = 0; i < n; i++)322strbuf_add(sb, s, len);323}
324
325void strbuf_addbuf(struct strbuf *sb, const struct strbuf *sb2)326{
327strbuf_grow(sb, sb2->len);328memcpy(sb->buf + sb->len, sb2->buf, sb2->len);329strbuf_setlen(sb, sb->len + sb2->len);330}
331
332const char *strbuf_join_argv(struct strbuf *buf,333int argc, const char **argv, char delim)334{
335if (!argc)336return buf->buf;337
338strbuf_addstr(buf, *argv);339while (--argc) {340strbuf_addch(buf, delim);341strbuf_addstr(buf, *(++argv));342}343
344return buf->buf;345}
346
347void strbuf_addchars(struct strbuf *sb, int c, size_t n)348{
349strbuf_grow(sb, n);350memset(sb->buf + sb->len, c, n);351strbuf_setlen(sb, sb->len + n);352}
353
354void strbuf_addf(struct strbuf *sb, const char *fmt, ...)355{
356va_list ap;357va_start(ap, fmt);358strbuf_vaddf(sb, fmt, ap);359va_end(ap);360}
361
362static void add_lines(struct strbuf *out,363const char *prefix,364const char *buf, size_t size,365int space_after_prefix)366{
367while (size) {368const char *next = memchr(buf, '\n', size);369next = next ? (next + 1) : (buf + size);370
371strbuf_addstr(out, prefix);372if (space_after_prefix && buf[0] != '\n' && buf[0] != '\t')373strbuf_addch(out, ' ');374strbuf_add(out, buf, next - buf);375size -= next - buf;376buf = next;377}378strbuf_complete_line(out);379}
380
381void strbuf_add_commented_lines(struct strbuf *out, const char *buf,382size_t size, const char *comment_prefix)383{
384add_lines(out, comment_prefix, buf, size, 1);385}
386
387void strbuf_commented_addf(struct strbuf *sb, const char *comment_prefix,388const char *fmt, ...)389{
390va_list params;391struct strbuf buf = STRBUF_INIT;392int incomplete_line = sb->len && sb->buf[sb->len - 1] != '\n';393
394va_start(params, fmt);395strbuf_vaddf(&buf, fmt, params);396va_end(params);397
398strbuf_add_commented_lines(sb, buf.buf, buf.len, comment_prefix);399if (incomplete_line)400sb->buf[--sb->len] = '\0';401
402strbuf_release(&buf);403}
404
405void strbuf_vaddf(struct strbuf *sb, const char *fmt, va_list ap)406{
407int len;408va_list cp;409
410if (!strbuf_avail(sb))411strbuf_grow(sb, 64);412va_copy(cp, ap);413len = vsnprintf(sb->buf + sb->len, sb->alloc - sb->len, fmt, cp);414va_end(cp);415if (len < 0)416die(_("unable to format message: %s"), fmt);417if (len > strbuf_avail(sb)) {418strbuf_grow(sb, len);419len = vsnprintf(sb->buf + sb->len, sb->alloc - sb->len, fmt, ap);420if (len > strbuf_avail(sb))421BUG("your vsnprintf is broken (insatiable)");422}423strbuf_setlen(sb, sb->len + len);424}
425
426int strbuf_expand_step(struct strbuf *sb, const char **formatp)427{
428const char *format = *formatp;429const char *percent = strchrnul(format, '%');430
431strbuf_add(sb, format, percent - format);432if (!*percent)433return 0;434*formatp = percent + 1;435return 1;436}
437
438size_t strbuf_expand_literal(struct strbuf *sb, const char *placeholder)439{
440int ch;441
442switch (placeholder[0]) {443case 'n': /* newline */444strbuf_addch(sb, '\n');445return 1;446case 'x':447/* %x00 == NUL, %x0a == LF, etc. */448ch = hex2chr(placeholder + 1);449if (ch < 0)450return 0;451strbuf_addch(sb, ch);452return 3;453}454return 0;455}
456
457void strbuf_expand_bad_format(const char *format, const char *command)458{
459const char *end;460
461if (*format != '(')462/* TRANSLATORS: The first %s is a command like "ls-tree". */463die(_("bad %s format: element '%s' does not start with '('"),464command, format);465
466end = strchr(format + 1, ')');467if (!end)468/* TRANSLATORS: The first %s is a command like "ls-tree". */469die(_("bad %s format: element '%s' does not end in ')'"),470command, format);471
472/* TRANSLATORS: %s is a command like "ls-tree". */473die(_("bad %s format: %%%.*s"),474command, (int)(end - format + 1), format);475}
476
477void strbuf_addbuf_percentquote(struct strbuf *dst, const struct strbuf *src)478{
479size_t i, len = src->len;480
481for (i = 0; i < len; i++) {482if (src->buf[i] == '%')483strbuf_addch(dst, '%');484strbuf_addch(dst, src->buf[i]);485}486}
487
488#define URL_UNSAFE_CHARS " <>\"%{}|\\^`:?#[]@!$&'()*+,;="489
490void strbuf_add_percentencode(struct strbuf *dst, const char *src, int flags)491{
492size_t i, len = strlen(src);493
494for (i = 0; i < len; i++) {495unsigned char ch = src[i];496if (ch <= 0x1F || ch >= 0x7F ||497(ch == '/' && (flags & STRBUF_ENCODE_SLASH)) ||498strchr(URL_UNSAFE_CHARS, ch))499strbuf_addf(dst, "%%%02X", (unsigned char)ch);500else501strbuf_addch(dst, ch);502}503}
504
505size_t strbuf_fread(struct strbuf *sb, size_t size, FILE *f)506{
507size_t res;508size_t oldalloc = sb->alloc;509
510strbuf_grow(sb, size);511res = fread(sb->buf + sb->len, 1, size, f);512if (res > 0)513strbuf_setlen(sb, sb->len + res);514else if (oldalloc == 0)515strbuf_release(sb);516return res;517}
518
519ssize_t strbuf_read(struct strbuf *sb, int fd, size_t hint)520{
521size_t oldlen = sb->len;522size_t oldalloc = sb->alloc;523
524strbuf_grow(sb, hint ? hint : 8192);525for (;;) {526ssize_t want = sb->alloc - sb->len - 1;527ssize_t got = read_in_full(fd, sb->buf + sb->len, want);528
529if (got < 0) {530if (oldalloc == 0)531strbuf_release(sb);532else533strbuf_setlen(sb, oldlen);534return -1;535}536sb->len += got;537if (got < want)538break;539strbuf_grow(sb, 8192);540}541
542sb->buf[sb->len] = '\0';543return sb->len - oldlen;544}
545
546ssize_t strbuf_read_once(struct strbuf *sb, int fd, size_t hint)547{
548size_t oldalloc = sb->alloc;549ssize_t cnt;550
551strbuf_grow(sb, hint ? hint : 8192);552cnt = xread(fd, sb->buf + sb->len, sb->alloc - sb->len - 1);553if (cnt > 0)554strbuf_setlen(sb, sb->len + cnt);555else if (oldalloc == 0)556strbuf_release(sb);557return cnt;558}
559
560ssize_t strbuf_write(struct strbuf *sb, FILE *f)561{
562return sb->len ? fwrite(sb->buf, 1, sb->len, f) : 0;563}
564
565#define STRBUF_MAXLINK (2*PATH_MAX)566
567int strbuf_readlink(struct strbuf *sb, const char *path, size_t hint)568{
569size_t oldalloc = sb->alloc;570
571if (hint < 32)572hint = 32;573
574while (hint < STRBUF_MAXLINK) {575ssize_t len;576
577strbuf_grow(sb, hint);578len = readlink(path, sb->buf, hint);579if (len < 0) {580if (errno != ERANGE)581break;582} else if (len < hint) {583strbuf_setlen(sb, len);584return 0;585}586
587/* .. the buffer was too small - try again */588hint *= 2;589}590if (oldalloc == 0)591strbuf_release(sb);592return -1;593}
594
595int strbuf_getcwd(struct strbuf *sb)596{
597size_t oldalloc = sb->alloc;598size_t guessed_len = 128;599
600for (;; guessed_len *= 2) {601strbuf_grow(sb, guessed_len);602if (getcwd(sb->buf, sb->alloc)) {603strbuf_setlen(sb, strlen(sb->buf));604return 0;605}606
607/*608* If getcwd(3) is implemented as a syscall that falls
609* back to a regular lookup using readdir(3) etc. then
610* we may be able to avoid EACCES by providing enough
611* space to the syscall as it's not necessarily bound
612* to the same restrictions as the fallback.
613*/
614if (errno == EACCES && guessed_len < PATH_MAX)615continue;616
617if (errno != ERANGE)618break;619}620if (oldalloc == 0)621strbuf_release(sb);622else623strbuf_reset(sb);624return -1;625}
626
627#ifdef HAVE_GETDELIM628int strbuf_getwholeline(struct strbuf *sb, FILE *fp, int term)629{
630ssize_t r;631
632if (feof(fp))633return EOF;634
635strbuf_reset(sb);636
637/* Translate slopbuf to NULL, as we cannot call realloc on it */638if (!sb->alloc)639sb->buf = NULL;640errno = 0;641r = getdelim(&sb->buf, &sb->alloc, term, fp);642
643if (r > 0) {644sb->len = r;645return 0;646}647assert(r == -1);648
649/*650* Normally we would have called xrealloc, which will try to free
651* memory and recover. But we have no way to tell getdelim() to do so.
652* Worse, we cannot try to recover ENOMEM ourselves, because we have
653* no idea how many bytes were read by getdelim.
654*
655* Dying here is reasonable. It mirrors what xrealloc would do on
656* catastrophic memory failure. We skip the opportunity to free pack
657* memory and retry, but that's unlikely to help for a malloc small
658* enough to hold a single line of input, anyway.
659*/
660if (errno == ENOMEM)661die("Out of memory, getdelim failed");662
663/*664* Restore strbuf invariants; if getdelim left us with a NULL pointer,
665* we can just re-init, but otherwise we should make sure that our
666* length is empty, and that the result is NUL-terminated.
667*/
668if (!sb->buf)669strbuf_init(sb, 0);670else671strbuf_reset(sb);672return EOF;673}
674#else675int strbuf_getwholeline(struct strbuf *sb, FILE *fp, int term)676{
677int ch;678
679if (feof(fp))680return EOF;681
682strbuf_reset(sb);683flockfile(fp);684while ((ch = getc_unlocked(fp)) != EOF) {685if (!strbuf_avail(sb))686strbuf_grow(sb, 1);687sb->buf[sb->len++] = ch;688if (ch == term)689break;690}691funlockfile(fp);692if (ch == EOF && sb->len == 0)693return EOF;694
695sb->buf[sb->len] = '\0';696return 0;697}
698#endif699
700int strbuf_appendwholeline(struct strbuf *sb, FILE *fp, int term)701{
702struct strbuf line = STRBUF_INIT;703if (strbuf_getwholeline(&line, fp, term)) {704strbuf_release(&line);705return EOF;706}707strbuf_addbuf(sb, &line);708strbuf_release(&line);709return 0;710}
711
712static int strbuf_getdelim(struct strbuf *sb, FILE *fp, int term)713{
714if (strbuf_getwholeline(sb, fp, term))715return EOF;716if (sb->buf[sb->len - 1] == term)717strbuf_setlen(sb, sb->len - 1);718return 0;719}
720
721int strbuf_getdelim_strip_crlf(struct strbuf *sb, FILE *fp, int term)722{
723if (strbuf_getwholeline(sb, fp, term))724return EOF;725if (term == '\n' && sb->buf[sb->len - 1] == '\n') {726strbuf_setlen(sb, sb->len - 1);727if (sb->len && sb->buf[sb->len - 1] == '\r')728strbuf_setlen(sb, sb->len - 1);729}730return 0;731}
732
733int strbuf_getline(struct strbuf *sb, FILE *fp)734{
735return strbuf_getdelim_strip_crlf(sb, fp, '\n');736}
737
738int strbuf_getline_lf(struct strbuf *sb, FILE *fp)739{
740return strbuf_getdelim(sb, fp, '\n');741}
742
743int strbuf_getline_nul(struct strbuf *sb, FILE *fp)744{
745return strbuf_getdelim(sb, fp, '\0');746}
747
748int strbuf_getwholeline_fd(struct strbuf *sb, int fd, int term)749{
750strbuf_reset(sb);751
752while (1) {753char ch;754ssize_t len = xread(fd, &ch, 1);755if (len <= 0)756return EOF;757strbuf_addch(sb, ch);758if (ch == term)759break;760}761return 0;762}
763
764ssize_t strbuf_read_file(struct strbuf *sb, const char *path, size_t hint)765{
766int fd;767ssize_t len;768int saved_errno;769
770fd = open(path, O_RDONLY);771if (fd < 0)772return -1;773len = strbuf_read(sb, fd, hint);774saved_errno = errno;775close(fd);776if (len < 0) {777errno = saved_errno;778return -1;779}780
781return len;782}
783
784void strbuf_add_lines(struct strbuf *out, const char *prefix,785const char *buf, size_t size)786{
787add_lines(out, prefix, buf, size, 0);788}
789
790void strbuf_addstr_xml_quoted(struct strbuf *buf, const char *s)791{
792while (*s) {793size_t len = strcspn(s, "\"<>&");794strbuf_add(buf, s, len);795s += len;796switch (*s) {797case '"':798strbuf_addstr(buf, """);799break;800case '<':801strbuf_addstr(buf, "<");802break;803case '>':804strbuf_addstr(buf, ">");805break;806case '&':807strbuf_addstr(buf, "&");808break;809case 0:810return;811}812s++;813}814}
815
816static void strbuf_add_urlencode(struct strbuf *sb, const char *s, size_t len,817char_predicate allow_unencoded_fn)818{
819strbuf_grow(sb, len);820while (len--) {821char ch = *s++;822if (allow_unencoded_fn(ch))823strbuf_addch(sb, ch);824else825strbuf_addf(sb, "%%%02x", (unsigned char)ch);826}827}
828
829void strbuf_addstr_urlencode(struct strbuf *sb, const char *s,830char_predicate allow_unencoded_fn)831{
832strbuf_add_urlencode(sb, s, strlen(s), allow_unencoded_fn);833}
834
835static void strbuf_humanise(struct strbuf *buf, off_t bytes,836int humanise_rate)837{
838if (bytes > 1 << 30) {839strbuf_addf(buf,840humanise_rate == 0 ?841/* TRANSLATORS: IEC 80000-13:2008 gibibyte */842_("%u.%2.2u GiB") :843/* TRANSLATORS: IEC 80000-13:2008 gibibyte/second */844_("%u.%2.2u GiB/s"),845(unsigned)(bytes >> 30),846(unsigned)(bytes & ((1 << 30) - 1)) / 10737419);847} else if (bytes > 1 << 20) {848unsigned x = bytes + 5243; /* for rounding */849strbuf_addf(buf,850humanise_rate == 0 ?851/* TRANSLATORS: IEC 80000-13:2008 mebibyte */852_("%u.%2.2u MiB") :853/* TRANSLATORS: IEC 80000-13:2008 mebibyte/second */854_("%u.%2.2u MiB/s"),855x >> 20, ((x & ((1 << 20) - 1)) * 100) >> 20);856} else if (bytes > 1 << 10) {857unsigned x = bytes + 5; /* for rounding */858strbuf_addf(buf,859humanise_rate == 0 ?860/* TRANSLATORS: IEC 80000-13:2008 kibibyte */861_("%u.%2.2u KiB") :862/* TRANSLATORS: IEC 80000-13:2008 kibibyte/second */863_("%u.%2.2u KiB/s"),864x >> 10, ((x & ((1 << 10) - 1)) * 100) >> 10);865} else {866strbuf_addf(buf,867humanise_rate == 0 ?868/* TRANSLATORS: IEC 80000-13:2008 byte */869Q_("%u byte", "%u bytes", bytes) :870/* TRANSLATORS: IEC 80000-13:2008 byte/second */871Q_("%u byte/s", "%u bytes/s", bytes),872(unsigned)bytes);873}874}
875
876void strbuf_humanise_bytes(struct strbuf *buf, off_t bytes)877{
878strbuf_humanise(buf, bytes, 0);879}
880
881void strbuf_humanise_rate(struct strbuf *buf, off_t bytes)882{
883strbuf_humanise(buf, bytes, 1);884}
885
886int printf_ln(const char *fmt, ...)887{
888int ret;889va_list ap;890va_start(ap, fmt);891ret = vprintf(fmt, ap);892va_end(ap);893if (ret < 0 || putchar('\n') == EOF)894return -1;895return ret + 1;896}
897
898int fprintf_ln(FILE *fp, const char *fmt, ...)899{
900int ret;901va_list ap;902va_start(ap, fmt);903ret = vfprintf(fp, fmt, ap);904va_end(ap);905if (ret < 0 || putc('\n', fp) == EOF)906return -1;907return ret + 1;908}
909
910char *xstrdup_tolower(const char *string)911{
912char *result;913size_t len, i;914
915len = strlen(string);916result = xmallocz(len);917for (i = 0; i < len; i++)918result[i] = tolower(string[i]);919return result;920}
921
922char *xstrdup_toupper(const char *string)923{
924char *result;925size_t len, i;926
927len = strlen(string);928result = xmallocz(len);929for (i = 0; i < len; i++)930result[i] = toupper(string[i]);931return result;932}
933
934char *xstrvfmt(const char *fmt, va_list ap)935{
936struct strbuf buf = STRBUF_INIT;937strbuf_vaddf(&buf, fmt, ap);938return strbuf_detach(&buf, NULL);939}
940
941char *xstrfmt(const char *fmt, ...)942{
943va_list ap;944char *ret;945
946va_start(ap, fmt);947ret = xstrvfmt(fmt, ap);948va_end(ap);949
950return ret;951}
952
953void strbuf_addftime(struct strbuf *sb, const char *fmt, const struct tm *tm,954int tz_offset, int suppress_tz_name)955{
956struct strbuf munged_fmt = STRBUF_INIT;957size_t hint = 128;958size_t len;959
960if (!*fmt)961return;962
963/*964* There is no portable way to pass timezone information to
965* strftime, so we handle %z and %Z here. Likewise '%s', because
966* going back to an epoch time requires knowing the zone.
967*
968* Note that tz_offset is in the "[-+]HHMM" decimal form; this is what
969* we want for %z, but the computation for %s has to convert to number
970* of seconds.
971*/
972while (strbuf_expand_step(&munged_fmt, &fmt)) {973if (skip_prefix(fmt, "%", &fmt))974strbuf_addstr(&munged_fmt, "%%");975else if (skip_prefix(fmt, "s", &fmt))976strbuf_addf(&munged_fmt, "%"PRItime,977(timestamp_t)tm_to_time_t(tm) -9783600 * (tz_offset / 100) -97960 * (tz_offset % 100));980else if (skip_prefix(fmt, "z", &fmt))981strbuf_addf(&munged_fmt, "%+05d", tz_offset);982else if (suppress_tz_name && skip_prefix(fmt, "Z", &fmt))983; /* nothing */984else985strbuf_addch(&munged_fmt, '%');986}987fmt = munged_fmt.buf;988
989strbuf_grow(sb, hint);990len = strftime(sb->buf + sb->len, sb->alloc - sb->len, fmt, tm);991
992if (!len) {993/*994* strftime reports "0" if it could not fit the result in the buffer.
995* Unfortunately, it also reports "0" if the requested time string
996* takes 0 bytes. So our strategy is to munge the format so that the
997* output contains at least one character, and then drop the extra
998* character before returning.
999*/
1000strbuf_addch(&munged_fmt, ' ');1001while (!len) {1002hint *= 2;1003strbuf_grow(sb, hint);1004len = strftime(sb->buf + sb->len, sb->alloc - sb->len,1005munged_fmt.buf, tm);1006}1007len--; /* drop munged space */1008}1009strbuf_release(&munged_fmt);1010strbuf_setlen(sb, sb->len + len);1011}
1012
1013/*
1014* Returns the length of a line, without trailing spaces.
1015*
1016* If the line ends with newline, it will be removed too.
1017*/
1018static size_t cleanup(char *line, size_t len)1019{
1020while (len) {1021unsigned char c = line[len - 1];1022if (!isspace(c))1023break;1024len--;1025}1026
1027return len;1028}
1029
1030/*
1031* Remove empty lines from the beginning and end
1032* and also trailing spaces from every line.
1033*
1034* Turn multiple consecutive empty lines between paragraphs
1035* into just one empty line.
1036*
1037* If the input has only empty lines and spaces,
1038* no output will be produced.
1039*
1040* If last line does not have a newline at the end, one is added.
1041*
1042* Pass a non-NULL comment_prefix to skip every line starting
1043* with it.
1044*/
1045void strbuf_stripspace(struct strbuf *sb, const char *comment_prefix)1046{
1047size_t empties = 0;1048size_t i, j, len, newlen;1049char *eol;1050
1051/* We may have to add a newline. */1052strbuf_grow(sb, 1);1053
1054for (i = j = 0; i < sb->len; i += len, j += newlen) {1055eol = memchr(sb->buf + i, '\n', sb->len - i);1056len = eol ? eol - (sb->buf + i) + 1 : sb->len - i;1057
1058if (comment_prefix && len &&1059starts_with(sb->buf + i, comment_prefix)) {1060newlen = 0;1061continue;1062}1063newlen = cleanup(sb->buf + i, len);1064
1065/* Not just an empty line? */1066if (newlen) {1067if (empties > 0 && j > 0)1068sb->buf[j++] = '\n';1069empties = 0;1070memmove(sb->buf + j, sb->buf + i, newlen);1071sb->buf[newlen + j++] = '\n';1072} else {1073empties++;1074}1075}1076
1077strbuf_setlen(sb, j);1078}
1079
1080void strbuf_strip_file_from_path(struct strbuf *sb)1081{
1082char *path_sep = find_last_dir_sep(sb->buf);1083strbuf_setlen(sb, path_sep ? path_sep - sb->buf + 1 : 0);1084}
1085