Changeset f47696f


Ignore:
Timestamp:
Jan 20, 2011, 7:59:38 PM (10 years ago)
Author:
David Benjamin <davidben@mit.edu>
Branches:
master, release-1.8, release-1.9
Children:
c426bc2
Parents:
443dcfa
git-author:
Nelson Elhage <nelhage@mit.edu> (01/03/11 21:18:17)
git-committer:
David Benjamin <davidben@mit.edu> (01/20/11 19:59:38)
Message:
Add owl_string_appendf_quoted for easy construction of command lines.
Files:
2 edited

Legend:

Unmodified
Added
Removed
  • tester.c

    r443dcfa rf47696f  
    215215                "\"");
    216216
     217  GString *g = g_string_new("");
     218  owl_string_appendf_quoted(g, "%q foo %q%q %s %", "hello", "world is", "can't");
     219  FAIL_UNLESS("owl_string_appendf",
     220              !strcmp(g_string_free(g, false),
     221                      "hello foo 'world is'\"can't\" %s %"));
     222
    217223  /* if (numfailed) printf("*** WARNING: failures encountered with owl_util\n"); */
    218224  printf("# END testing owl_util (%d failures)\n", numfailed);
  • util.c

    r2bc6ad35 rf47696f  
    88#include <sys/types.h>
    99#include <assert.h>
     10#include <stdarg.h>
    1011#include <glib.h>
    1112#include <glib/gstdio.h>
     
    226227}
    227228
     229/*
     230 * Appends 'tmpl' to 'buf', replacing any instances of '%q' with arguments from
     231 * the varargs provided, quoting them to be safe for placing in a barnowl
     232 * command line.
     233 */
     234void owl_string_appendf_quoted(GString *buf, const char *tmpl, ...)
     235{
     236  va_list ap;
     237  va_start(ap, tmpl);
     238  owl_string_vappendf_quoted(buf, tmpl, ap);
     239  va_end(ap);
     240}
     241
     242void owl_string_vappendf_quoted(GString *buf, const char *tmpl, va_list ap)
     243{
     244  const char *p = tmpl, *last = tmpl;
     245  while (true) {
     246    p = strchr(p, '%');
     247    if (p == NULL) break;
     248    if (*(p+1) != 'q') {
     249      p++;
     250      if (*p) p++;
     251      continue;
     252    }
     253    g_string_append_len(buf, last, p - last);
     254    owl_string_append_quoted_arg(buf, va_arg(ap, char *));
     255    p += 2; last = p;
     256  }
     257
     258  g_string_append(buf, last);
     259}
     260
     261char *owl_string_build_quoted(const char *tmpl, ...)
     262{
     263  GString *buf = g_string_new("");
     264  va_list ap;
     265  va_start(ap, tmpl);
     266  owl_string_vappendf_quoted(buf, tmpl, ap);
     267  va_end(ap);
     268  return g_string_free(buf, false); 
     269}
     270
    228271/* Returns a quoted version of arg suitable for placing in a
    229272 * command-line. Result should be freed with owl_free. */
Note: See TracChangeset for help on using the changeset viewer.