strbuf.con commit setup: convert setup_git_directory_gently_1 et al. to strbuf (7333ed1)
   1#include "cache.h"
   2#include "refs.h"
   3
   4int starts_with(const char *str, const char *prefix)
   5{
   6        for (; ; str++, prefix++)
   7                if (!*prefix)
   8                        return 1;
   9                else if (*str != *prefix)
  10                        return 0;
  11}
  12
  13int ends_with(const char *str, const char *suffix)
  14{
  15        int len = strlen(str), suflen = strlen(suffix);
  16        if (len < suflen)
  17                return 0;
  18        else
  19                return !strcmp(str + len - suflen, suffix);
  20}
  21
  22/*
  23 * Used as the default ->buf value, so that people can always assume
  24 * buf is non NULL and ->buf is NUL terminated even for a freshly
  25 * initialized strbuf.
  26 */
  27char strbuf_slopbuf[1];
  28
  29void strbuf_init(struct strbuf *sb, size_t hint)
  30{
  31        sb->alloc = sb->len = 0;
  32        sb->buf = strbuf_slopbuf;
  33        if (hint)
  34                strbuf_grow(sb, hint);
  35}
  36
  37void strbuf_release(struct strbuf *sb)
  38{
  39        if (sb->alloc) {
  40                free(sb->buf);
  41                strbuf_init(sb, 0);
  42        }
  43}
  44
  45char *strbuf_detach(struct strbuf *sb, size_t *sz)
  46{
  47        char *res;
  48        strbuf_grow(sb, 0);
  49        res = sb->buf;
  50        if (sz)
  51                *sz = sb->len;
  52        strbuf_init(sb, 0);
  53        return res;
  54}
  55
  56void strbuf_attach(struct strbuf *sb, void *buf, size_t len, size_t alloc)
  57{
  58        strbuf_release(sb);
  59        sb->buf   = buf;
  60        sb->len   = len;
  61        sb->alloc = alloc;
  62        strbuf_grow(sb, 0);
  63        sb->buf[sb->len] = '\0';
  64}
  65
  66void strbuf_grow(struct strbuf *sb, size_t extra)
  67{
  68        int new_buf = !sb->alloc;
  69        if (unsigned_add_overflows(extra, 1) ||
  70            unsigned_add_overflows(sb->len, extra + 1))
  71                die("you want to use way too much memory");
  72        if (new_buf)
  73                sb->buf = NULL;
  74        ALLOC_GROW(sb->buf, sb->len + extra + 1, sb->alloc);
  75        if (new_buf)
  76                sb->buf[0] = '\0';
  77}
  78
  79void strbuf_trim(struct strbuf *sb)
  80{
  81        char *b = sb->buf;
  82        while (sb->len > 0 && isspace((unsigned char)sb->buf[sb->len - 1]))
  83                sb->len--;
  84        while (sb->len > 0 && isspace(*b)) {
  85                b++;
  86                sb->len--;
  87        }
  88        memmove(sb->buf, b, sb->len);
  89        sb->buf[sb->len] = '\0';
  90}
  91void strbuf_rtrim(struct strbuf *sb)
  92{
  93        while (sb->len > 0 && isspace((unsigned char)sb->buf[sb->len - 1]))
  94                sb->len--;
  95        sb->buf[sb->len] = '\0';
  96}
  97
  98void strbuf_ltrim(struct strbuf *sb)
  99{
 100        char *b = sb->buf;
 101        while (sb->len > 0 && isspace(*b)) {
 102                b++;
 103                sb->len--;
 104        }
 105        memmove(sb->buf, b, sb->len);
 106        sb->buf[sb->len] = '\0';
 107}
 108
 109struct strbuf **strbuf_split_buf(const char *str, size_t slen,
 110                                 int terminator, int max)
 111{
 112        struct strbuf **ret = NULL;
 113        size_t nr = 0, alloc = 0;
 114        struct strbuf *t;
 115
 116        while (slen) {
 117                int len = slen;
 118                if (max <= 0 || nr + 1 < max) {
 119                        const char *end = memchr(str, terminator, slen);
 120                        if (end)
 121                                len = end - str + 1;
 122                }
 123                t = xmalloc(sizeof(struct strbuf));
 124                strbuf_init(t, len);
 125                strbuf_add(t, str, len);
 126                ALLOC_GROW(ret, nr + 2, alloc);
 127                ret[nr++] = t;
 128                str += len;
 129                slen -= len;
 130        }
 131        ALLOC_GROW(ret, nr + 1, alloc); /* In case string was empty */
 132        ret[nr] = NULL;
 133        return ret;
 134}
 135
 136void strbuf_list_free(struct strbuf **sbs)
 137{
 138        struct strbuf **s = sbs;
 139
 140        while (*s) {
 141                strbuf_release(*s);
 142                free(*s++);
 143        }
 144        free(sbs);
 145}
 146
 147int strbuf_cmp(const struct strbuf *a, const struct strbuf *b)
 148{
 149        int len = a->len < b->len ? a->len: b->len;
 150        int cmp = memcmp(a->buf, b->buf, len);
 151        if (cmp)
 152                return cmp;
 153        return a->len < b->len ? -1: a->len != b->len;
 154}
 155
 156void strbuf_splice(struct strbuf *sb, size_t pos, size_t len,
 157                                   const void *data, size_t dlen)
 158{
 159        if (unsigned_add_overflows(pos, len))
 160                die("you want to use way too much memory");
 161        if (pos > sb->len)
 162                die("`pos' is too far after the end of the buffer");
 163        if (pos + len > sb->len)
 164                die("`pos + len' is too far after the end of the buffer");
 165
 166        if (dlen >= len)
 167                strbuf_grow(sb, dlen - len);
 168        memmove(sb->buf + pos + dlen,
 169                        sb->buf + pos + len,
 170                        sb->len - pos - len);
 171        memcpy(sb->buf + pos, data, dlen);
 172        strbuf_setlen(sb, sb->len + dlen - len);
 173}
 174
 175void strbuf_insert(struct strbuf *sb, size_t pos, const void *data, size_t len)
 176{
 177        strbuf_splice(sb, pos, 0, data, len);
 178}
 179
 180void strbuf_remove(struct strbuf *sb, size_t pos, size_t len)
 181{
 182        strbuf_splice(sb, pos, len, NULL, 0);
 183}
 184
 185void strbuf_add(struct strbuf *sb, const void *data, size_t len)
 186{
 187        strbuf_grow(sb, len);
 188        memcpy(sb->buf + sb->len, data, len);
 189        strbuf_setlen(sb, sb->len + len);
 190}
 191
 192void strbuf_adddup(struct strbuf *sb, size_t pos, size_t len)
 193{
 194        strbuf_grow(sb, len);
 195        memcpy(sb->buf + sb->len, sb->buf + pos, len);
 196        strbuf_setlen(sb, sb->len + len);
 197}
 198
 199void strbuf_addf(struct strbuf *sb, const char *fmt, ...)
 200{
 201        va_list ap;
 202        va_start(ap, fmt);
 203        strbuf_vaddf(sb, fmt, ap);
 204        va_end(ap);
 205}
 206
 207static void add_lines(struct strbuf *out,
 208                        const char *prefix1,
 209                        const char *prefix2,
 210                        const char *buf, size_t size)
 211{
 212        while (size) {
 213                const char *prefix;
 214                const char *next = memchr(buf, '\n', size);
 215                next = next ? (next + 1) : (buf + size);
 216
 217                prefix = (prefix2 && buf[0] == '\n') ? prefix2 : prefix1;
 218                strbuf_addstr(out, prefix);
 219                strbuf_add(out, buf, next - buf);
 220                size -= next - buf;
 221                buf = next;
 222        }
 223        strbuf_complete_line(out);
 224}
 225
 226void strbuf_add_commented_lines(struct strbuf *out, const char *buf, size_t size)
 227{
 228        static char prefix1[3];
 229        static char prefix2[2];
 230
 231        if (prefix1[0] != comment_line_char) {
 232                sprintf(prefix1, "%c ", comment_line_char);
 233                sprintf(prefix2, "%c", comment_line_char);
 234        }
 235        add_lines(out, prefix1, prefix2, buf, size);
 236}
 237
 238void strbuf_commented_addf(struct strbuf *sb, const char *fmt, ...)
 239{
 240        va_list params;
 241        struct strbuf buf = STRBUF_INIT;
 242        int incomplete_line = sb->len && sb->buf[sb->len - 1] != '\n';
 243
 244        va_start(params, fmt);
 245        strbuf_vaddf(&buf, fmt, params);
 246        va_end(params);
 247
 248        strbuf_add_commented_lines(sb, buf.buf, buf.len);
 249        if (incomplete_line)
 250                sb->buf[--sb->len] = '\0';
 251
 252        strbuf_release(&buf);
 253}
 254
 255void strbuf_vaddf(struct strbuf *sb, const char *fmt, va_list ap)
 256{
 257        int len;
 258        va_list cp;
 259
 260        if (!strbuf_avail(sb))
 261                strbuf_grow(sb, 64);
 262        va_copy(cp, ap);
 263        len = vsnprintf(sb->buf + sb->len, sb->alloc - sb->len, fmt, cp);
 264        va_end(cp);
 265        if (len < 0)
 266                die("BUG: your vsnprintf is broken (returned %d)", len);
 267        if (len > strbuf_avail(sb)) {
 268                strbuf_grow(sb, len);
 269                len = vsnprintf(sb->buf + sb->len, sb->alloc - sb->len, fmt, ap);
 270                if (len > strbuf_avail(sb))
 271                        die("BUG: your vsnprintf is broken (insatiable)");
 272        }
 273        strbuf_setlen(sb, sb->len + len);
 274}
 275
 276void strbuf_expand(struct strbuf *sb, const char *format, expand_fn_t fn,
 277                   void *context)
 278{
 279        for (;;) {
 280                const char *percent;
 281                size_t consumed;
 282
 283                percent = strchrnul(format, '%');
 284                strbuf_add(sb, format, percent - format);
 285                if (!*percent)
 286                        break;
 287                format = percent + 1;
 288
 289                if (*format == '%') {
 290                        strbuf_addch(sb, '%');
 291                        format++;
 292                        continue;
 293                }
 294
 295                consumed = fn(sb, format, context);
 296                if (consumed)
 297                        format += consumed;
 298                else
 299                        strbuf_addch(sb, '%');
 300        }
 301}
 302
 303size_t strbuf_expand_dict_cb(struct strbuf *sb, const char *placeholder,
 304                void *context)
 305{
 306        struct strbuf_expand_dict_entry *e = context;
 307        size_t len;
 308
 309        for (; e->placeholder && (len = strlen(e->placeholder)); e++) {
 310                if (!strncmp(placeholder, e->placeholder, len)) {
 311                        if (e->value)
 312                                strbuf_addstr(sb, e->value);
 313                        return len;
 314                }
 315        }
 316        return 0;
 317}
 318
 319void strbuf_addbuf_percentquote(struct strbuf *dst, const struct strbuf *src)
 320{
 321        int i, len = src->len;
 322
 323        for (i = 0; i < len; i++) {
 324                if (src->buf[i] == '%')
 325                        strbuf_addch(dst, '%');
 326                strbuf_addch(dst, src->buf[i]);
 327        }
 328}
 329
 330size_t strbuf_fread(struct strbuf *sb, size_t size, FILE *f)
 331{
 332        size_t res;
 333        size_t oldalloc = sb->alloc;
 334
 335        strbuf_grow(sb, size);
 336        res = fread(sb->buf + sb->len, 1, size, f);
 337        if (res > 0)
 338                strbuf_setlen(sb, sb->len + res);
 339        else if (oldalloc == 0)
 340                strbuf_release(sb);
 341        return res;
 342}
 343
 344ssize_t strbuf_read(struct strbuf *sb, int fd, size_t hint)
 345{
 346        size_t oldlen = sb->len;
 347        size_t oldalloc = sb->alloc;
 348
 349        strbuf_grow(sb, hint ? hint : 8192);
 350        for (;;) {
 351                ssize_t cnt;
 352
 353                cnt = xread(fd, sb->buf + sb->len, sb->alloc - sb->len - 1);
 354                if (cnt < 0) {
 355                        if (oldalloc == 0)
 356                                strbuf_release(sb);
 357                        else
 358                                strbuf_setlen(sb, oldlen);
 359                        return -1;
 360                }
 361                if (!cnt)
 362                        break;
 363                sb->len += cnt;
 364                strbuf_grow(sb, 8192);
 365        }
 366
 367        sb->buf[sb->len] = '\0';
 368        return sb->len - oldlen;
 369}
 370
 371#define STRBUF_MAXLINK (2*PATH_MAX)
 372
 373int strbuf_readlink(struct strbuf *sb, const char *path, size_t hint)
 374{
 375        size_t oldalloc = sb->alloc;
 376
 377        if (hint < 32)
 378                hint = 32;
 379
 380        while (hint < STRBUF_MAXLINK) {
 381                int len;
 382
 383                strbuf_grow(sb, hint);
 384                len = readlink(path, sb->buf, hint);
 385                if (len < 0) {
 386                        if (errno != ERANGE)
 387                                break;
 388                } else if (len < hint) {
 389                        strbuf_setlen(sb, len);
 390                        return 0;
 391                }
 392
 393                /* .. the buffer was too small - try again */
 394                hint *= 2;
 395        }
 396        if (oldalloc == 0)
 397                strbuf_release(sb);
 398        return -1;
 399}
 400
 401int strbuf_getcwd(struct strbuf *sb)
 402{
 403        size_t oldalloc = sb->alloc;
 404        size_t guessed_len = 128;
 405
 406        for (;; guessed_len *= 2) {
 407                strbuf_grow(sb, guessed_len);
 408                if (getcwd(sb->buf, sb->alloc)) {
 409                        strbuf_setlen(sb, strlen(sb->buf));
 410                        return 0;
 411                }
 412                if (errno != ERANGE)
 413                        break;
 414        }
 415        if (oldalloc == 0)
 416                strbuf_release(sb);
 417        else
 418                strbuf_reset(sb);
 419        return -1;
 420}
 421
 422int strbuf_getwholeline(struct strbuf *sb, FILE *fp, int term)
 423{
 424        int ch;
 425
 426        if (feof(fp))
 427                return EOF;
 428
 429        strbuf_reset(sb);
 430        while ((ch = fgetc(fp)) != EOF) {
 431                strbuf_grow(sb, 1);
 432                sb->buf[sb->len++] = ch;
 433                if (ch == term)
 434                        break;
 435        }
 436        if (ch == EOF && sb->len == 0)
 437                return EOF;
 438
 439        sb->buf[sb->len] = '\0';
 440        return 0;
 441}
 442
 443int strbuf_getline(struct strbuf *sb, FILE *fp, int term)
 444{
 445        if (strbuf_getwholeline(sb, fp, term))
 446                return EOF;
 447        if (sb->buf[sb->len-1] == term)
 448                strbuf_setlen(sb, sb->len-1);
 449        return 0;
 450}
 451
 452int strbuf_getwholeline_fd(struct strbuf *sb, int fd, int term)
 453{
 454        strbuf_reset(sb);
 455
 456        while (1) {
 457                char ch;
 458                ssize_t len = xread(fd, &ch, 1);
 459                if (len <= 0)
 460                        return EOF;
 461                strbuf_addch(sb, ch);
 462                if (ch == term)
 463                        break;
 464        }
 465        return 0;
 466}
 467
 468int strbuf_read_file(struct strbuf *sb, const char *path, size_t hint)
 469{
 470        int fd, len;
 471
 472        fd = open(path, O_RDONLY);
 473        if (fd < 0)
 474                return -1;
 475        len = strbuf_read(sb, fd, hint);
 476        close(fd);
 477        if (len < 0)
 478                return -1;
 479
 480        return len;
 481}
 482
 483void strbuf_add_lines(struct strbuf *out, const char *prefix,
 484                      const char *buf, size_t size)
 485{
 486        add_lines(out, prefix, NULL, buf, size);
 487}
 488
 489void strbuf_addstr_xml_quoted(struct strbuf *buf, const char *s)
 490{
 491        while (*s) {
 492                size_t len = strcspn(s, "\"<>&");
 493                strbuf_add(buf, s, len);
 494                s += len;
 495                switch (*s) {
 496                case '"':
 497                        strbuf_addstr(buf, "&quot;");
 498                        break;
 499                case '<':
 500                        strbuf_addstr(buf, "&lt;");
 501                        break;
 502                case '>':
 503                        strbuf_addstr(buf, "&gt;");
 504                        break;
 505                case '&':
 506                        strbuf_addstr(buf, "&amp;");
 507                        break;
 508                case 0:
 509                        return;
 510                }
 511                s++;
 512        }
 513}
 514
 515static int is_rfc3986_reserved(char ch)
 516{
 517        switch (ch) {
 518                case '!': case '*': case '\'': case '(': case ')': case ';':
 519                case ':': case '@': case '&': case '=': case '+': case '$':
 520                case ',': case '/': case '?': case '#': case '[': case ']':
 521                        return 1;
 522        }
 523        return 0;
 524}
 525
 526static int is_rfc3986_unreserved(char ch)
 527{
 528        return isalnum(ch) ||
 529                ch == '-' || ch == '_' || ch == '.' || ch == '~';
 530}
 531
 532static void strbuf_add_urlencode(struct strbuf *sb, const char *s, size_t len,
 533                                 int reserved)
 534{
 535        strbuf_grow(sb, len);
 536        while (len--) {
 537                char ch = *s++;
 538                if (is_rfc3986_unreserved(ch) ||
 539                    (!reserved && is_rfc3986_reserved(ch)))
 540                        strbuf_addch(sb, ch);
 541                else
 542                        strbuf_addf(sb, "%%%02x", ch);
 543        }
 544}
 545
 546void strbuf_addstr_urlencode(struct strbuf *sb, const char *s,
 547                             int reserved)
 548{
 549        strbuf_add_urlencode(sb, s, strlen(s), reserved);
 550}
 551
 552void strbuf_humanise_bytes(struct strbuf *buf, off_t bytes)
 553{
 554        if (bytes > 1 << 30) {
 555                strbuf_addf(buf, "%u.%2.2u GiB",
 556                            (int)(bytes >> 30),
 557                            (int)(bytes & ((1 << 30) - 1)) / 10737419);
 558        } else if (bytes > 1 << 20) {
 559                int x = bytes + 5243;  /* for rounding */
 560                strbuf_addf(buf, "%u.%2.2u MiB",
 561                            x >> 20, ((x & ((1 << 20) - 1)) * 100) >> 20);
 562        } else if (bytes > 1 << 10) {
 563                int x = bytes + 5;  /* for rounding */
 564                strbuf_addf(buf, "%u.%2.2u KiB",
 565                            x >> 10, ((x & ((1 << 10) - 1)) * 100) >> 10);
 566        } else {
 567                strbuf_addf(buf, "%u bytes", (int)bytes);
 568        }
 569}
 570
 571int printf_ln(const char *fmt, ...)
 572{
 573        int ret;
 574        va_list ap;
 575        va_start(ap, fmt);
 576        ret = vprintf(fmt, ap);
 577        va_end(ap);
 578        if (ret < 0 || putchar('\n') == EOF)
 579                return -1;
 580        return ret + 1;
 581}
 582
 583int fprintf_ln(FILE *fp, const char *fmt, ...)
 584{
 585        int ret;
 586        va_list ap;
 587        va_start(ap, fmt);
 588        ret = vfprintf(fp, fmt, ap);
 589        va_end(ap);
 590        if (ret < 0 || putc('\n', fp) == EOF)
 591                return -1;
 592        return ret + 1;
 593}