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