Subject: [PATCH 1/3] trace: implement %p placeholder for filenames

From: Jeff King <[email-masked]>
Date: Tue, 16 Jun 2015 15:35:32 -0400

This lets you trace output on a per-process basis by naming
the trace file after the PID. This is probably not all that
useful for GIT_TRACE itself (which is about a global view of
the process hierarchy anyway), but will be useful for traces
which produce large amounts of data (e.g., whole packfiles).

Signed-off-by: Jeff King <[email-masked]>
---
This is the bare minimum to let you distinguish between the stdin of
different processes. If we are going to use the trace subsystem to
collect more long-term debugging logs, it would probably make sense to
add placeholders for the program name and a timestamp. Then you could,
for example, leave more verbose debugging enabled on your servers all
the time.

 Documentation/git.txt |  3 ++-
 trace.c               | 19 +++++++++++++++++--
 2 files changed, 19 insertions(+), 3 deletions(-)

diff --git a/Documentation/git.txt b/Documentation/git.txt
index 3453669..80f6392 100644
--- a/Documentation/git.txt
+++ b/Documentation/git.txt
@@ -984,7 +984,8 @@ trace messages into this file descriptor.
 Alternatively, if the variable is set to an absolute path
 (starting with a '/' character), Git will interpret this
 as a file path and will try to write the trace messages
-into it.
+into it. If the filename contains the string `%p`, that string
+will be replaced with the PID of the traced process.
 +
 Unsetting the variable, or setting it to empty, "0" or
 "false" (case insensitive) disables trace messages.
diff --git a/trace.c b/trace.c
index 7393926..e1d1360 100644
--- a/trace.c
+++ b/trace.c
@@ -25,6 +25,16 @@
 #include "cache.h"
 #include "quote.h"
 
+static size_t expand_trace_name(struct strbuf *out, const char *fmt,
+				void *data)
+{
+	if (*fmt == 'p') {
+		strbuf_addf(out, "%lu", (unsigned long)getpid());
+		return 1;
+	}
+	return 0;
+}
+
 /* Get a trace file descriptor from "key" env variable. */
 static int get_trace_fd(struct trace_key *key)
 {
@@ -49,17 +59,22 @@ static int get_trace_fd(struct trace_key *key)
 	else if (strlen(trace) == 1 && isdigit(*trace))
 		key->fd = atoi(trace);
 	else if (is_absolute_path(trace)) {
-		int fd = open(trace, O_WRONLY | O_APPEND | O_CREAT, 0666);
+		struct strbuf name = STRBUF_INIT;
+		int fd;
+
+		strbuf_expand(&name, trace, expand_trace_name, NULL);
+		fd = open(name.buf, O_WRONLY | O_APPEND | O_CREAT, 0666);
 		if (fd == -1) {
 			fprintf(stderr,
 				"Could not open '%s' for tracing: %s\n"
 				"Defaulting to tracing on stderr...\n",
-				trace, strerror(errno));
+				name.buf, strerror(errno));
 			key->fd = STDERR_FILENO;
 		} else {
 			key->fd = fd;
 			key->need_close = 1;
 		}
+		strbuf_release(&name);
 	} else {
 		fprintf(stderr, "What does '%s' for %s mean?\n"
 			"If you want to trace into a file, then please set "
-- 
2.4.3.699.g84b4da7