]> Dogcows Code - chaz/githead/commitdiff
add escaping for non-printable characters master
authorCharles McGarvey <chazmcgarvey@brokenzipper.com>
Mon, 18 Mar 2013 21:14:36 +0000 (15:14 -0600)
committerCharles McGarvey <chazmcgarvey@brokenzipper.com>
Mon, 18 Mar 2013 21:14:36 +0000 (15:14 -0600)
githead.c

index e258a5b314ee506860ac7af7d0da621f060d980b..c75b0720b7dfd187ea4e59b6496793df3fa12c49 100644 (file)
--- a/githead.c
+++ b/githead.c
  * Written 04 June 2012 by Charles McGarvey.
  */
 
+const char* format = "\ 1\e[%sm\ 2 %s\ 1\e[0m\ 2";
 const char* ansi_codes = "0;36";
 const char* ansi_codes_dirty = "0;31";
 
+const int short_hash_length = 7;
+
 #include <errno.h>
 #include <regex.h>
 #include <stdio.h>
@@ -31,9 +34,8 @@ const char* ansi_codes_dirty = "0;31";
 
 int main(int argc, char* argv[])
 {
-    char buf[4096];
-
-    char*   branch = NULL;
+    char    buf[4096];
+    char*   ref = NULL;
     int     dirty = 0;
 
     fclose(stderr);     // usually do not want any extra junk printed
@@ -141,7 +143,44 @@ int main(int argc, char* argv[])
            return 1;
        }
        buf[bytes-1] = '\0';
-       branch = buf + 11;
+       ref = buf + 11;
+    } else {
+        if (pipe(p) == -1) {
+            fprintf(stderr, "pipe failed: %s\n", strerror(errno));
+            return 1;
+        }
+
+        pid_t pid4 = fork();
+        if (pid4 == -1) {
+            fprintf(stderr, "fork failed: %s\n", strerror(errno));
+            return 1;
+        }
+        if (pid4 == 0) {
+            char* args[] = {"git", "rev-parse", "HEAD", NULL};
+            if (dup2(p[1], 1) == -1) {
+                fprintf(stderr, "dup2 failed: %s\n", strerror(errno));
+            }
+            execvp(args[0], args);
+            return 1;
+        }
+
+        close(p[1]);
+
+        while (waitpid(pid4, &status, 0) < 0) {
+            if (errno != EINTR) {
+                fprintf(stderr, "waitpid failed: %s\n", strerror(errno));
+                return 1;
+            }
+        }
+        if (WEXITSTATUS(status) == 0) {
+            ssize_t bytes = read(p[0], buf, sizeof(buf));
+            if (bytes < 0) {
+                fprintf(stderr, "read failed: %s\n", strerror(errno));
+                return 1;
+            }
+            buf[short_hash_length] = '\0';
+            ref = buf;
+        }
     }
 
     while (waitpid(pid2, &status, 0) < 0) {
@@ -152,12 +191,12 @@ int main(int argc, char* argv[])
     }
     dirty = (WEXITSTATUS(status) != 0);
 
-    if (branch) {
+    if (ref) {
        if (dirty) {
-           printf("\033[%sm[%s]\033[0m", ansi_codes_dirty, branch);
+           printf(format, ansi_codes_dirty, ref);
        }
        else {
-           printf("\033[%sm[%s]\033[0m", ansi_codes, branch);
+           printf(format, ansi_codes, ref);
        }
     }
 
This page took 0.064398 seconds and 4 git commands to generate.