]>
Dogcows Code - chaz/githead/blob - githead.c
e258a5b314ee506860ac7af7d0da621f060d980b
3 * Get the name of the current git branch (pointed to by HEAD) and print it
4 * out, color-coded to show if any working files are dirty. This would
5 * ideally be implemented as a shell script, but I wrote it in C because it
6 * needs to be fast! And we all know C is fast, amiright?
8 * Also reads in regular expressions (one per line) matching paths that
9 * should be ignored. Each regex is matched against the top-level
10 * directory path of the repository. If it matches, nothing is printed.
11 * It is a good idea to ignore repositories on slow (remote) disks.
13 * Example usage (bash):
14 * PS1='\u@\h \w$(githead <~/.nogitprompt) $ '
16 * Written 04 June 2012 by Charles McGarvey.
19 const char* ansi_codes
= "0;36";
20 const char* ansi_codes_dirty
= "0;31";
29 #include <sys/types.h>
32 int main(int argc
, char* argv
[])
39 fclose(stderr
); // usually do not want any extra junk printed
43 fprintf(stderr
, "pipe failed: %s\n", strerror(errno
));
49 fprintf(stderr
, "fork failed: %s\n", strerror(errno
));
53 char* args
[] = {"git", "rev-parse", "--show-toplevel", NULL
};
54 if (dup2(p
[1], 1) == -1) {
55 fprintf(stderr
, "dup2 failed: %s\n", strerror(errno
));
57 execvp(args
[0], args
);
64 while (waitpid(pid1
, &status
, 0) < 0) {
66 fprintf(stderr
, "waitpid failed: %s\n", strerror(errno
));
70 if (WEXITSTATUS(status
) == 0) {
71 ssize_t bytes
= read(p
[0], buf
, sizeof(buf
));
73 fprintf(stderr
, "read failed: %s\n", strerror(errno
));
79 while (gets(regbuf
)) {
82 int err
= regcomp(&re
, regbuf
, REG_EXTENDED
| REG_ICASE
| REG_NOSUB
);
84 regerror(err
, &re
, errbuf
, sizeof(errbuf
));
85 fprintf(stderr
, "regcomp failed: %s\n", errbuf
);
88 if (regexec(&re
, buf
, 0, NULL
, 0) == 0) {
95 fprintf(stderr
, "git failed; bailing out...\n");
101 fprintf(stderr
, "fork failed: %s\n", strerror(errno
));
105 char* args
[] = {"git", "diff", "--no-ext-diff", "--quiet", "--exit-code", NULL
};
106 execvp(args
[0], args
);
111 fprintf(stderr
, "pipe failed: %s\n", strerror(errno
));
117 fprintf(stderr
, "fork failed: %s\n", strerror(errno
));
121 char* args
[] = {"git", "symbolic-ref", "HEAD", NULL
};
122 if (dup2(p
[1], 1) == -1) {
123 fprintf(stderr
, "dup2 failed: %s\n", strerror(errno
));
125 execvp(args
[0], args
);
131 while (waitpid(pid3
, &status
, 0) < 0) {
132 if (errno
!= EINTR
) {
133 fprintf(stderr
, "waitpid failed: %s\n", strerror(errno
));
137 if (WEXITSTATUS(status
) == 0) {
138 ssize_t bytes
= read(p
[0], buf
, sizeof(buf
));
140 fprintf(stderr
, "read failed: %s\n", strerror(errno
));
147 while (waitpid(pid2
, &status
, 0) < 0) {
148 if (errno
!= EINTR
) {
149 fprintf(stderr
, "waitpid failed: %s\n", strerror(errno
));
153 dirty
= (WEXITSTATUS(status
) != 0);
157 printf("\033[%sm[%s]\033[0m", ansi_codes_dirty
, branch
);
160 printf("\033[%sm[%s]\033[0m", ansi_codes
, branch
);
This page took 0.038866 seconds and 3 git commands to generate.