Imported Upstream version 2.28.0
[platform/upstream/git.git] / usage.c
diff --git a/usage.c b/usage.c
index cc80333..58fb5ff 100644 (file)
--- a/usage.c
+++ b/usage.c
@@ -9,30 +9,73 @@
 void vreportf(const char *prefix, const char *err, va_list params)
 {
        char msg[4096];
-       char *p;
+       char *p, *pend = msg + sizeof(msg);
+       size_t prefix_len = strlen(prefix);
 
-       vsnprintf(msg, sizeof(msg), err, params);
-       for (p = msg; *p; p++) {
+       if (sizeof(msg) <= prefix_len) {
+               fprintf(stderr, "BUG!!! too long a prefix '%s'\n", prefix);
+               abort();
+       }
+       memcpy(msg, prefix, prefix_len);
+       p = msg + prefix_len;
+       if (vsnprintf(p, pend - p, err, params) < 0)
+               *p = '\0'; /* vsnprintf() failed, clip at prefix */
+
+       for (; p != pend - 1 && *p; p++) {
                if (iscntrl(*p) && *p != '\t' && *p != '\n')
                        *p = '?';
        }
-       fprintf(stderr, "%s%s\n", prefix, msg);
+
+       *(p++) = '\n'; /* we no longer need a NUL */
+       fflush(stderr);
+       write_in_full(2, msg, p - msg);
 }
 
 static NORETURN void usage_builtin(const char *err, va_list params)
 {
        vreportf("usage: ", err, params);
+
+       /*
+        * When we detect a usage error *before* the command dispatch in
+        * cmd_main(), we don't know what verb to report.  Force it to this
+        * to facilitate post-processing.
+        */
+       trace2_cmd_name("_usage_");
+
+       /*
+        * Currently, the (err, params) are usually just the static usage
+        * string which isn't very useful here.  Usually, the call site
+        * manually calls fprintf(stderr,...) with the actual detailed
+        * syntax error before calling usage().
+        *
+        * TODO It would be nice to update the call sites to pass both
+        * the static usage string and the detailed error message.
+        */
+
        exit(129);
 }
 
 static NORETURN void die_builtin(const char *err, va_list params)
 {
+       /*
+        * We call this trace2 function first and expect it to va_copy 'params'
+        * before using it (because an 'ap' can only be walked once).
+        */
+       trace2_cmd_error_va(err, params);
+
        vreportf("fatal: ", err, params);
+
        exit(128);
 }
 
 static void error_builtin(const char *err, va_list params)
 {
+       /*
+        * We call this trace2 function first and expect it to va_copy 'params'
+        * before using it (because an 'ap' can only be walked once).
+        */
+       trace2_cmd_error_va(err, params);
+
        vreportf("error: ", err, params);
 }