patch-id: extract parsing one diff out of generate_id_list
[git/gitweb.git] / builtin / patch-id.c
blob973d830ecfed016553088eae83b97c6c74201bfb
1 #include "cache.h"
2 #include "exec_cmd.h"
4 static void flush_current_id(int patchlen, unsigned char *id, git_SHA_CTX *c)
6 unsigned char result[20];
7 char name[50];
9 if (!patchlen)
10 return;
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);
18 static int remove_space(char *line)
20 char *src = line;
21 char *dst = line;
22 unsigned char c;
24 while ((c = *src++) != '\0') {
25 if (!isspace(c))
26 *dst++ = c;
28 return dst - line;
31 int get_one_patchid(unsigned char *next_sha1, git_SHA_CTX *ctx)
33 static char line[1000];
34 int patchlen = 0, found_next = 0;
36 while (fgets(line, sizeof(line), stdin) != NULL) {
37 char *p = line;
38 int len;
40 if (!memcmp(line, "diff-tree ", 10))
41 p += 10;
42 else if (!memcmp(line, "commit ", 7))
43 p += 7;
45 if (!get_sha1_hex(p, next_sha1)) {
46 found_next = 1;
47 break;
50 /* Ignore commit comments */
51 if (!patchlen && memcmp(line, "diff ", 5))
52 continue;
54 /* Ignore git-diff index header */
55 if (!memcmp(line, "index ", 6))
56 continue;
58 /* Ignore line numbers when computing the SHA1 of the patch */
59 if (!memcmp(line, "@@ -", 4))
60 continue;
62 /* Compute the sha without whitespace */
63 len = remove_space(line);
64 patchlen += len;
65 git_SHA1_Update(ctx, line, len);
68 if (!found_next)
69 hashclr(next_sha1);
71 return patchlen;
74 static void generate_id_list(void)
76 unsigned char sha1[20], n[20];
77 git_SHA_CTX ctx;
78 int patchlen;
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);
89 static const char patch_id_usage[] = "git patch-id < patch";
91 int cmd_patch_id(int argc, const char **argv, const char *prefix)
93 if (argc != 1)
94 usage(patch_id_usage);
96 generate_id_list();
97 return 0;