tripectl: Quotify the arguments rather than hoping for the best.
[tripe] / common / util.c
index ceeb0bd..4b32985 100644 (file)
 #include <unistd.h>
 #include <fcntl.h>
 
+#include <mLib/dstr.h>
+
 #include "util.h"
 
 #include <sys/ioctl.h>
 
 /*----- Main code ---------------------------------------------------------*/
 
+/* --- @u_quotify@ --- *
+ *
+ * Arguments:  @dstr *d@ = where to write the answer
+ *             @const char *p@ = string to quotify
+ *
+ * Returns:    ---
+ *
+ * Use:                Quotes the given string if necessary, according to our
+ *             quoting rules.
+ */
+
+void u_quotify(dstr *d, const char *p)
+{
+  if (d->len)
+    dstr_putc(d, ' ');
+  if (*p && !p[strcspn(p, "\"' \t\n\v")])
+    dstr_puts(d, p);
+  else {
+    dstr_putc(d, '\"');
+    while (*p) {
+      if (*p == '\\' || *p == '\"')
+       dstr_putc(d, '\\');
+      dstr_putc(d, *p++);
+    }
+    dstr_putc(d, '\"');
+  }
+}
+
 /* --- @u_detach@ --- *
  *
  * Arguments:  ---