]> git.ipfire.org Git - thirdparty/git.git/blob - write-tree.c
Add copyright notices.
[thirdparty/git.git] / write-tree.c
1 /*
2 * GIT - The information manager from hell
3 *
4 * Copyright (C) Linus Torvalds, 2005
5 */
6 #include "cache.h"
7
8 static int check_valid_sha1(unsigned char *sha1)
9 {
10 char *filename = sha1_file_name(sha1);
11 int ret;
12
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;
18 }
19
20 static int prepend_integer(char *buffer, unsigned val, int i)
21 {
22 buffer[--i] = '\0';
23 do {
24 buffer[--i] = '0' + (val % 10);
25 val /= 10;
26 } while (val);
27 return i;
28 }
29
30 #define ORIG_OFFSET (40) /* Enough space to add the header of "tree <size>\0" */
31
32 int main(int argc, char **argv)
33 {
34 unsigned long size, offset, val;
35 int i, entries = read_cache();
36 char *buffer;
37
38 if (entries <= 0) {
39 fprintf(stderr, "No file-cache to create a tree of\n");
40 exit(1);
41 }
42
43 /* Guess at an initial size */
44 size = entries * 40 + 400;
45 buffer = malloc(size);
46 offset = ORIG_OFFSET;
47
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);
55 }
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;
60 }
61
62 i = prepend_integer(buffer, offset - ORIG_OFFSET, ORIG_OFFSET);
63 i -= 5;
64 memcpy(buffer+i, "tree ", 5);
65
66 buffer += i;
67 offset -= i;
68
69 write_sha1_file(buffer, offset);
70 return 0;
71 }