* 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>
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
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) {
}
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);
}
}