]> asedeno.scripts.mit.edu Git - git.git/blob - builtin/patch-id.c
973d830ecfed016553088eae83b97c6c74201bfb
[git.git] / builtin / patch-id.c
1 #include "cache.h"
2 #include "exec_cmd.h"
3
4 static void flush_current_id(int patchlen, unsigned char *id, git_SHA_CTX *c)
5 {
6         unsigned char result[20];
7         char name[50];
8
9         if (!patchlen)
10                 return;
11
12         git_SHA1_Final(result, c);
13         memcpy(name, sha1_to_hex(id), 41);
14         printf("%s %s\n", sha1_to_hex(result), name);
15         git_SHA1_Init(c);
16 }
17
18 static int remove_space(char *line)
19 {
20         char *src = line;
21         char *dst = line;
22         unsigned char c;
23
24         while ((c = *src++) != '\0') {
25                 if (!isspace(c))
26                         *dst++ = c;
27         }
28         return dst - line;
29 }
30
31 int get_one_patchid(unsigned char *next_sha1, git_SHA_CTX *ctx)
32 {
33         static char line[1000];
34         int patchlen = 0, found_next = 0;
35
36         while (fgets(line, sizeof(line), stdin) != NULL) {
37                 char *p = line;
38                 int len;
39
40                 if (!memcmp(line, "diff-tree ", 10))
41                         p += 10;
42                 else if (!memcmp(line, "commit ", 7))
43                         p += 7;
44
45                 if (!get_sha1_hex(p, next_sha1)) {
46                         found_next = 1;
47                         break;
48                 }
49
50                 /* Ignore commit comments */
51                 if (!patchlen && memcmp(line, "diff ", 5))
52                         continue;
53
54                 /* Ignore git-diff index header */
55                 if (!memcmp(line, "index ", 6))
56                         continue;
57
58                 /* Ignore line numbers when computing the SHA1 of the patch */
59                 if (!memcmp(line, "@@ -", 4))
60                         continue;
61
62                 /* Compute the sha without whitespace */
63                 len = remove_space(line);
64                 patchlen += len;
65                 git_SHA1_Update(ctx, line, len);
66         }
67
68         if (!found_next)
69                 hashclr(next_sha1);
70
71         return patchlen;
72 }
73
74 static void generate_id_list(void)
75 {
76         unsigned char sha1[20], n[20];
77         git_SHA_CTX ctx;
78         int patchlen;
79
80         git_SHA1_Init(&ctx);
81         hashclr(sha1);
82         while (!feof(stdin)) {
83                 patchlen = get_one_patchid(n, &ctx);
84                 flush_current_id(patchlen, sha1, &ctx);
85                 hashcpy(sha1, n);
86         }
87 }
88
89 static const char patch_id_usage[] = "git patch-id < patch";
90
91 int cmd_patch_id(int argc, const char **argv, const char *prefix)
92 {
93         if (argc != 1)
94                 usage(patch_id_usage);
95
96         generate_id_list();
97         return 0;
98 }