Merge branch 'ls/complete-remote-update-names'
[git] / t / helper / test-sha1.c
1 #include "test-tool.h"
2 #include "cache.h"
3
4 int cmd__sha1(int ac, const char **av)
5 {
6         git_SHA_CTX ctx;
7         unsigned char sha1[20];
8         unsigned bufsz = 8192;
9         int binary = 0;
10         char *buffer;
11
12         if (ac == 2) {
13                 if (!strcmp(av[1], "-b"))
14                         binary = 1;
15                 else
16                         bufsz = strtoul(av[1], NULL, 10) * 1024 * 1024;
17         }
18
19         if (!bufsz)
20                 bufsz = 8192;
21
22         while ((buffer = malloc(bufsz)) == NULL) {
23                 fprintf(stderr, "bufsz %u is too big, halving...\n", bufsz);
24                 bufsz /= 2;
25                 if (bufsz < 1024)
26                         die("OOPS");
27         }
28
29         git_SHA1_Init(&ctx);
30
31         while (1) {
32                 ssize_t sz, this_sz;
33                 char *cp = buffer;
34                 unsigned room = bufsz;
35                 this_sz = 0;
36                 while (room) {
37                         sz = xread(0, cp, room);
38                         if (sz == 0)
39                                 break;
40                         if (sz < 0)
41                                 die_errno("test-sha1");
42                         this_sz += sz;
43                         cp += sz;
44                         room -= sz;
45                 }
46                 if (this_sz == 0)
47                         break;
48                 git_SHA1_Update(&ctx, buffer, this_sz);
49         }
50         git_SHA1_Final(sha1, &ctx);
51
52         if (binary)
53                 fwrite(sha1, 1, 20, stdout);
54         else
55                 puts(sha1_to_hex(sha1));
56         exit(0);
57 }