From: Charles McGarvey Date: Mon, 18 Mar 2013 21:14:36 +0000 (-0600) Subject: add escaping for non-printable characters X-Git-Url: https://git.dogcows.com/gitweb?a=commitdiff_plain;ds=sidebyside;p=chaz%2Fgithead add escaping for non-printable characters --- diff --git a/githead.c b/githead.c index e258a5b..c75b072 100644 --- a/githead.c +++ b/githead.c @@ -16,9 +16,12 @@ * Written 04 June 2012 by Charles McGarvey. */ +const char* format = "[%sm %s"; const char* ansi_codes = "0;36"; const char* ansi_codes_dirty = "0;31"; +const int short_hash_length = 7; + #include #include #include @@ -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); } }