Make the cache stat information comparator public.
[git/dscho.git] / write-tree.c
blob6e531b40a84914cf1b37e12f8629fecbec0ae041
1 /*
2 * GIT - The information manager from hell
4 * Copyright (C) Linus Torvalds, 2005
5 */
6 #include "cache.h"
8 static int check_valid_sha1(unsigned char *sha1)
10 char *filename = sha1_file_name(sha1);
11 int ret;
13 /* If we were anal, we'd check that the sha1 of the contents actually matches */
14 ret = access(filename, R_OK);
15 if (ret)
16 perror(filename);
17 return ret;
20 static int prepend_integer(char *buffer, unsigned val, int i)
22 buffer[--i] = '\0';
23 do {
24 buffer[--i] = '0' + (val % 10);
25 val /= 10;
26 } while (val);
27 return i;
30 #define ORIG_OFFSET (40) /* Enough space to add the header of "tree <size>\0" */
32 int main(int argc, char **argv)
34 unsigned long size, offset;
35 int i, entries = read_cache();
36 char *buffer;
38 if (entries <= 0) {
39 fprintf(stderr, "No file-cache to create a tree of\n");
40 exit(1);
43 /* Guess at an initial size */
44 size = entries * 40 + 400;
45 buffer = malloc(size);
46 offset = ORIG_OFFSET;
48 for (i = 0; i < entries; i++) {
49 struct cache_entry *ce = active_cache[i];
50 if (check_valid_sha1(ce->sha1) < 0)
51 exit(1);
52 if (offset + ce->namelen + 60 > size) {
53 size = alloc_nr(offset + ce->namelen + 60);
54 buffer = realloc(buffer, size);
56 offset += sprintf(buffer + offset, "%o %s", ce->st_mode, ce->name);
57 buffer[offset++] = 0;
58 memcpy(buffer + offset, ce->sha1, 20);
59 offset += 20;
62 i = prepend_integer(buffer, offset - ORIG_OFFSET, ORIG_OFFSET);
63 i -= 5;
64 memcpy(buffer+i, "tree ", 5);
66 buffer += i;
67 offset -= i;
69 write_sha1_file(buffer, offset);
70 return 0;