Code

grep documentation: clarify what files match
[git.git] / fast-import.c
1 /*
2 (See Documentation/git-fast-import.txt for maintained documentation.)
3 Format of STDIN stream:
5   stream ::= cmd*;
7   cmd ::= new_blob
8         | new_commit
9         | new_tag
10         | reset_branch
11         | checkpoint
12         | progress
13         ;
15   new_blob ::= 'blob' lf
16     mark?
17     file_content;
18   file_content ::= data;
20   new_commit ::= 'commit' sp ref_str lf
21     mark?
22     ('author' (sp name)? sp '<' email '>' sp when lf)?
23     'committer' (sp name)? sp '<' email '>' sp when lf
24     commit_msg
25     ('from' sp committish lf)?
26     ('merge' sp committish lf)*
27     file_change*
28     lf?;
29   commit_msg ::= data;
31   file_change ::= file_clr
32     | file_del
33     | file_rnm
34     | file_cpy
35     | file_obm
36     | file_inm;
37   file_clr ::= 'deleteall' lf;
38   file_del ::= 'D' sp path_str lf;
39   file_rnm ::= 'R' sp path_str sp path_str lf;
40   file_cpy ::= 'C' sp path_str sp path_str lf;
41   file_obm ::= 'M' sp mode sp (hexsha1 | idnum) sp path_str lf;
42   file_inm ::= 'M' sp mode sp 'inline' sp path_str lf
43     data;
44   note_obm ::= 'N' sp (hexsha1 | idnum) sp committish lf;
45   note_inm ::= 'N' sp 'inline' sp committish lf
46     data;
48   new_tag ::= 'tag' sp tag_str lf
49     'from' sp committish lf
50     ('tagger' (sp name)? sp '<' email '>' sp when lf)?
51     tag_msg;
52   tag_msg ::= data;
54   reset_branch ::= 'reset' sp ref_str lf
55     ('from' sp committish lf)?
56     lf?;
58   checkpoint ::= 'checkpoint' lf
59     lf?;
61   progress ::= 'progress' sp not_lf* lf
62     lf?;
64      # note: the first idnum in a stream should be 1 and subsequent
65      # idnums should not have gaps between values as this will cause
66      # the stream parser to reserve space for the gapped values.  An
67      # idnum can be updated in the future to a new object by issuing
68      # a new mark directive with the old idnum.
69      #
70   mark ::= 'mark' sp idnum lf;
71   data ::= (delimited_data | exact_data)
72     lf?;
74     # note: delim may be any string but must not contain lf.
75     # data_line may contain any data but must not be exactly
76     # delim.
77   delimited_data ::= 'data' sp '<<' delim lf
78     (data_line lf)*
79     delim lf;
81      # note: declen indicates the length of binary_data in bytes.
82      # declen does not include the lf preceding the binary data.
83      #
84   exact_data ::= 'data' sp declen lf
85     binary_data;
87      # note: quoted strings are C-style quoting supporting \c for
88      # common escapes of 'c' (e..g \n, \t, \\, \") or \nnn where nnn
89      # is the signed byte value in octal.  Note that the only
90      # characters which must actually be escaped to protect the
91      # stream formatting is: \, " and LF.  Otherwise these values
92      # are UTF8.
93      #
94   committish  ::= (ref_str | hexsha1 | sha1exp_str | idnum);
95   ref_str     ::= ref;
96   sha1exp_str ::= sha1exp;
97   tag_str     ::= tag;
98   path_str    ::= path    | '"' quoted(path)    '"' ;
99   mode        ::= '100644' | '644'
100                 | '100755' | '755'
101                 | '120000'
102                 ;
104   declen ::= # unsigned 32 bit value, ascii base10 notation;
105   bigint ::= # unsigned integer value, ascii base10 notation;
106   binary_data ::= # file content, not interpreted;
108   when         ::= raw_when | rfc2822_when;
109   raw_when     ::= ts sp tz;
110   rfc2822_when ::= # Valid RFC 2822 date and time;
112   sp ::= # ASCII space character;
113   lf ::= # ASCII newline (LF) character;
115      # note: a colon (':') must precede the numerical value assigned to
116      # an idnum.  This is to distinguish it from a ref or tag name as
117      # GIT does not permit ':' in ref or tag strings.
118      #
119   idnum   ::= ':' bigint;
120   path    ::= # GIT style file path, e.g. "a/b/c";
121   ref     ::= # GIT ref name, e.g. "refs/heads/MOZ_GECKO_EXPERIMENT";
122   tag     ::= # GIT tag name, e.g. "FIREFOX_1_5";
123   sha1exp ::= # Any valid GIT SHA1 expression;
124   hexsha1 ::= # SHA1 in hexadecimal format;
126      # note: name and email are UTF8 strings, however name must not
127      # contain '<' or lf and email must not contain any of the
128      # following: '<', '>', lf.
129      #
130   name  ::= # valid GIT author/committer name;
131   email ::= # valid GIT author/committer email;
132   ts    ::= # time since the epoch in seconds, ascii base10 notation;
133   tz    ::= # GIT style timezone;
135      # note: comments may appear anywhere in the input, except
136      # within a data command.  Any form of the data command
137      # always escapes the related input from comment processing.
138      #
139      # In case it is not clear, the '#' that starts the comment
140      # must be the first character on that line (an lf
141      # preceded it).
142      #
143   comment ::= '#' not_lf* lf;
144   not_lf  ::= # Any byte that is not ASCII newline (LF);
145 */
147 #include "builtin.h"
148 #include "cache.h"
149 #include "object.h"
150 #include "blob.h"
151 #include "tree.h"
152 #include "commit.h"
153 #include "delta.h"
154 #include "pack.h"
155 #include "refs.h"
156 #include "csum-file.h"
157 #include "quote.h"
158 #include "exec_cmd.h"
160 #define PACK_ID_BITS 16
161 #define MAX_PACK_ID ((1<<PACK_ID_BITS)-1)
162 #define DEPTH_BITS 13
163 #define MAX_DEPTH ((1<<DEPTH_BITS)-1)
165 struct object_entry
167         struct object_entry *next;
168         uint32_t offset;
169         uint32_t type : TYPE_BITS,
170                 pack_id : PACK_ID_BITS,
171                 depth : DEPTH_BITS;
172         unsigned char sha1[20];
173 };
175 struct object_entry_pool
177         struct object_entry_pool *next_pool;
178         struct object_entry *next_free;
179         struct object_entry *end;
180         struct object_entry entries[FLEX_ARRAY]; /* more */
181 };
183 struct mark_set
185         union {
186                 struct object_entry *marked[1024];
187                 struct mark_set *sets[1024];
188         } data;
189         unsigned int shift;
190 };
192 struct last_object
194         struct strbuf data;
195         uint32_t offset;
196         unsigned int depth;
197         unsigned no_swap : 1;
198 };
200 struct mem_pool
202         struct mem_pool *next_pool;
203         char *next_free;
204         char *end;
205         uintmax_t space[FLEX_ARRAY]; /* more */
206 };
208 struct atom_str
210         struct atom_str *next_atom;
211         unsigned short str_len;
212         char str_dat[FLEX_ARRAY]; /* more */
213 };
215 struct tree_content;
216 struct tree_entry
218         struct tree_content *tree;
219         struct atom_str *name;
220         struct tree_entry_ms
221         {
222                 uint16_t mode;
223                 unsigned char sha1[20];
224         } versions[2];
225 };
227 struct tree_content
229         unsigned int entry_capacity; /* must match avail_tree_content */
230         unsigned int entry_count;
231         unsigned int delta_depth;
232         struct tree_entry *entries[FLEX_ARRAY]; /* more */
233 };
235 struct avail_tree_content
237         unsigned int entry_capacity; /* must match tree_content */
238         struct avail_tree_content *next_avail;
239 };
241 struct branch
243         struct branch *table_next_branch;
244         struct branch *active_next_branch;
245         const char *name;
246         struct tree_entry branch_tree;
247         uintmax_t last_commit;
248         unsigned active : 1;
249         unsigned pack_id : PACK_ID_BITS;
250         unsigned char sha1[20];
251 };
253 struct tag
255         struct tag *next_tag;
256         const char *name;
257         unsigned int pack_id;
258         unsigned char sha1[20];
259 };
261 struct hash_list
263         struct hash_list *next;
264         unsigned char sha1[20];
265 };
267 typedef enum {
268         WHENSPEC_RAW = 1,
269         WHENSPEC_RFC2822,
270         WHENSPEC_NOW,
271 } whenspec_type;
273 struct recent_command
275         struct recent_command *prev;
276         struct recent_command *next;
277         char *buf;
278 };
280 /* Configured limits on output */
281 static unsigned long max_depth = 10;
282 static off_t max_packsize = (1LL << 32) - 1;
283 static uintmax_t big_file_threshold = 512 * 1024 * 1024;
284 static int force_update;
285 static int pack_compression_level = Z_DEFAULT_COMPRESSION;
286 static int pack_compression_seen;
288 /* Stats and misc. counters */
289 static uintmax_t alloc_count;
290 static uintmax_t marks_set_count;
291 static uintmax_t object_count_by_type[1 << TYPE_BITS];
292 static uintmax_t duplicate_count_by_type[1 << TYPE_BITS];
293 static uintmax_t delta_count_by_type[1 << TYPE_BITS];
294 static unsigned long object_count;
295 static unsigned long branch_count;
296 static unsigned long branch_load_count;
297 static int failure;
298 static FILE *pack_edges;
300 /* Memory pools */
301 static size_t mem_pool_alloc = 2*1024*1024 - sizeof(struct mem_pool);
302 static size_t total_allocd;
303 static struct mem_pool *mem_pool;
305 /* Atom management */
306 static unsigned int atom_table_sz = 4451;
307 static unsigned int atom_cnt;
308 static struct atom_str **atom_table;
310 /* The .pack file being generated */
311 static unsigned int pack_id;
312 static struct packed_git *pack_data;
313 static struct packed_git **all_packs;
314 static unsigned long pack_size;
316 /* Table of objects we've written. */
317 static unsigned int object_entry_alloc = 5000;
318 static struct object_entry_pool *blocks;
319 static struct object_entry *object_table[1 << 16];
320 static struct mark_set *marks;
321 static const char *mark_file;
323 /* Our last blob */
324 static struct last_object last_blob = { STRBUF_INIT, 0, 0, 0 };
326 /* Tree management */
327 static unsigned int tree_entry_alloc = 1000;
328 static void *avail_tree_entry;
329 static unsigned int avail_tree_table_sz = 100;
330 static struct avail_tree_content **avail_tree_table;
331 static struct strbuf old_tree = STRBUF_INIT;
332 static struct strbuf new_tree = STRBUF_INIT;
334 /* Branch data */
335 static unsigned long max_active_branches = 5;
336 static unsigned long cur_active_branches;
337 static unsigned long branch_table_sz = 1039;
338 static struct branch **branch_table;
339 static struct branch *active_branches;
341 /* Tag data */
342 static struct tag *first_tag;
343 static struct tag *last_tag;
345 /* Input stream parsing */
346 static whenspec_type whenspec = WHENSPEC_RAW;
347 static struct strbuf command_buf = STRBUF_INIT;
348 static int unread_command_buf;
349 static struct recent_command cmd_hist = {&cmd_hist, &cmd_hist, NULL};
350 static struct recent_command *cmd_tail = &cmd_hist;
351 static struct recent_command *rc_free;
352 static unsigned int cmd_save = 100;
353 static uintmax_t next_mark;
354 static struct strbuf new_data = STRBUF_INIT;
356 static void write_branch_report(FILE *rpt, struct branch *b)
358         fprintf(rpt, "%s:\n", b->name);
360         fprintf(rpt, "  status      :");
361         if (b->active)
362                 fputs(" active", rpt);
363         if (b->branch_tree.tree)
364                 fputs(" loaded", rpt);
365         if (is_null_sha1(b->branch_tree.versions[1].sha1))
366                 fputs(" dirty", rpt);
367         fputc('\n', rpt);
369         fprintf(rpt, "  tip commit  : %s\n", sha1_to_hex(b->sha1));
370         fprintf(rpt, "  old tree    : %s\n", sha1_to_hex(b->branch_tree.versions[0].sha1));
371         fprintf(rpt, "  cur tree    : %s\n", sha1_to_hex(b->branch_tree.versions[1].sha1));
372         fprintf(rpt, "  commit clock: %" PRIuMAX "\n", b->last_commit);
374         fputs("  last pack   : ", rpt);
375         if (b->pack_id < MAX_PACK_ID)
376                 fprintf(rpt, "%u", b->pack_id);
377         fputc('\n', rpt);
379         fputc('\n', rpt);
382 static void dump_marks_helper(FILE *, uintmax_t, struct mark_set *);
384 static void write_crash_report(const char *err)
386         char *loc = git_path("fast_import_crash_%"PRIuMAX, (uintmax_t) getpid());
387         FILE *rpt = fopen(loc, "w");
388         struct branch *b;
389         unsigned long lu;
390         struct recent_command *rc;
392         if (!rpt) {
393                 error("can't write crash report %s: %s", loc, strerror(errno));
394                 return;
395         }
397         fprintf(stderr, "fast-import: dumping crash report to %s\n", loc);
399         fprintf(rpt, "fast-import crash report:\n");
400         fprintf(rpt, "    fast-import process: %"PRIuMAX"\n", (uintmax_t) getpid());
401         fprintf(rpt, "    parent process     : %"PRIuMAX"\n", (uintmax_t) getppid());
402         fprintf(rpt, "    at %s\n", show_date(time(NULL), 0, DATE_LOCAL));
403         fputc('\n', rpt);
405         fputs("fatal: ", rpt);
406         fputs(err, rpt);
407         fputc('\n', rpt);
409         fputc('\n', rpt);
410         fputs("Most Recent Commands Before Crash\n", rpt);
411         fputs("---------------------------------\n", rpt);
412         for (rc = cmd_hist.next; rc != &cmd_hist; rc = rc->next) {
413                 if (rc->next == &cmd_hist)
414                         fputs("* ", rpt);
415                 else
416                         fputs("  ", rpt);
417                 fputs(rc->buf, rpt);
418                 fputc('\n', rpt);
419         }
421         fputc('\n', rpt);
422         fputs("Active Branch LRU\n", rpt);
423         fputs("-----------------\n", rpt);
424         fprintf(rpt, "    active_branches = %lu cur, %lu max\n",
425                 cur_active_branches,
426                 max_active_branches);
427         fputc('\n', rpt);
428         fputs("  pos  clock name\n", rpt);
429         fputs("  ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n", rpt);
430         for (b = active_branches, lu = 0; b; b = b->active_next_branch)
431                 fprintf(rpt, "  %2lu) %6" PRIuMAX" %s\n",
432                         ++lu, b->last_commit, b->name);
434         fputc('\n', rpt);
435         fputs("Inactive Branches\n", rpt);
436         fputs("-----------------\n", rpt);
437         for (lu = 0; lu < branch_table_sz; lu++) {
438                 for (b = branch_table[lu]; b; b = b->table_next_branch)
439                         write_branch_report(rpt, b);
440         }
442         if (first_tag) {
443                 struct tag *tg;
444                 fputc('\n', rpt);
445                 fputs("Annotated Tags\n", rpt);
446                 fputs("--------------\n", rpt);
447                 for (tg = first_tag; tg; tg = tg->next_tag) {
448                         fputs(sha1_to_hex(tg->sha1), rpt);
449                         fputc(' ', rpt);
450                         fputs(tg->name, rpt);
451                         fputc('\n', rpt);
452                 }
453         }
455         fputc('\n', rpt);
456         fputs("Marks\n", rpt);
457         fputs("-----\n", rpt);
458         if (mark_file)
459                 fprintf(rpt, "  exported to %s\n", mark_file);
460         else
461                 dump_marks_helper(rpt, 0, marks);
463         fputc('\n', rpt);
464         fputs("-------------------\n", rpt);
465         fputs("END OF CRASH REPORT\n", rpt);
466         fclose(rpt);
469 static void end_packfile(void);
470 static void unkeep_all_packs(void);
471 static void dump_marks(void);
473 static NORETURN void die_nicely(const char *err, va_list params)
475         static int zombie;
476         char message[2 * PATH_MAX];
478         vsnprintf(message, sizeof(message), err, params);
479         fputs("fatal: ", stderr);
480         fputs(message, stderr);
481         fputc('\n', stderr);
483         if (!zombie) {
484                 zombie = 1;
485                 write_crash_report(message);
486                 end_packfile();
487                 unkeep_all_packs();
488                 dump_marks();
489         }
490         exit(128);
493 static void alloc_objects(unsigned int cnt)
495         struct object_entry_pool *b;
497         b = xmalloc(sizeof(struct object_entry_pool)
498                 + cnt * sizeof(struct object_entry));
499         b->next_pool = blocks;
500         b->next_free = b->entries;
501         b->end = b->entries + cnt;
502         blocks = b;
503         alloc_count += cnt;
506 static struct object_entry *new_object(unsigned char *sha1)
508         struct object_entry *e;
510         if (blocks->next_free == blocks->end)
511                 alloc_objects(object_entry_alloc);
513         e = blocks->next_free++;
514         hashcpy(e->sha1, sha1);
515         return e;
518 static struct object_entry *find_object(unsigned char *sha1)
520         unsigned int h = sha1[0] << 8 | sha1[1];
521         struct object_entry *e;
522         for (e = object_table[h]; e; e = e->next)
523                 if (!hashcmp(sha1, e->sha1))
524                         return e;
525         return NULL;
528 static struct object_entry *insert_object(unsigned char *sha1)
530         unsigned int h = sha1[0] << 8 | sha1[1];
531         struct object_entry *e = object_table[h];
532         struct object_entry *p = NULL;
534         while (e) {
535                 if (!hashcmp(sha1, e->sha1))
536                         return e;
537                 p = e;
538                 e = e->next;
539         }
541         e = new_object(sha1);
542         e->next = NULL;
543         e->offset = 0;
544         if (p)
545                 p->next = e;
546         else
547                 object_table[h] = e;
548         return e;
551 static unsigned int hc_str(const char *s, size_t len)
553         unsigned int r = 0;
554         while (len-- > 0)
555                 r = r * 31 + *s++;
556         return r;
559 static void *pool_alloc(size_t len)
561         struct mem_pool *p;
562         void *r;
564         /* round up to a 'uintmax_t' alignment */
565         if (len & (sizeof(uintmax_t) - 1))
566                 len += sizeof(uintmax_t) - (len & (sizeof(uintmax_t) - 1));
568         for (p = mem_pool; p; p = p->next_pool)
569                 if ((p->end - p->next_free >= len))
570                         break;
572         if (!p) {
573                 if (len >= (mem_pool_alloc/2)) {
574                         total_allocd += len;
575                         return xmalloc(len);
576                 }
577                 total_allocd += sizeof(struct mem_pool) + mem_pool_alloc;
578                 p = xmalloc(sizeof(struct mem_pool) + mem_pool_alloc);
579                 p->next_pool = mem_pool;
580                 p->next_free = (char *) p->space;
581                 p->end = p->next_free + mem_pool_alloc;
582                 mem_pool = p;
583         }
585         r = p->next_free;
586         p->next_free += len;
587         return r;
590 static void *pool_calloc(size_t count, size_t size)
592         size_t len = count * size;
593         void *r = pool_alloc(len);
594         memset(r, 0, len);
595         return r;
598 static char *pool_strdup(const char *s)
600         char *r = pool_alloc(strlen(s) + 1);
601         strcpy(r, s);
602         return r;
605 static void insert_mark(uintmax_t idnum, struct object_entry *oe)
607         struct mark_set *s = marks;
608         while ((idnum >> s->shift) >= 1024) {
609                 s = pool_calloc(1, sizeof(struct mark_set));
610                 s->shift = marks->shift + 10;
611                 s->data.sets[0] = marks;
612                 marks = s;
613         }
614         while (s->shift) {
615                 uintmax_t i = idnum >> s->shift;
616                 idnum -= i << s->shift;
617                 if (!s->data.sets[i]) {
618                         s->data.sets[i] = pool_calloc(1, sizeof(struct mark_set));
619                         s->data.sets[i]->shift = s->shift - 10;
620                 }
621                 s = s->data.sets[i];
622         }
623         if (!s->data.marked[idnum])
624                 marks_set_count++;
625         s->data.marked[idnum] = oe;
628 static struct object_entry *find_mark(uintmax_t idnum)
630         uintmax_t orig_idnum = idnum;
631         struct mark_set *s = marks;
632         struct object_entry *oe = NULL;
633         if ((idnum >> s->shift) < 1024) {
634                 while (s && s->shift) {
635                         uintmax_t i = idnum >> s->shift;
636                         idnum -= i << s->shift;
637                         s = s->data.sets[i];
638                 }
639                 if (s)
640                         oe = s->data.marked[idnum];
641         }
642         if (!oe)
643                 die("mark :%" PRIuMAX " not declared", orig_idnum);
644         return oe;
647 static struct atom_str *to_atom(const char *s, unsigned short len)
649         unsigned int hc = hc_str(s, len) % atom_table_sz;
650         struct atom_str *c;
652         for (c = atom_table[hc]; c; c = c->next_atom)
653                 if (c->str_len == len && !strncmp(s, c->str_dat, len))
654                         return c;
656         c = pool_alloc(sizeof(struct atom_str) + len + 1);
657         c->str_len = len;
658         strncpy(c->str_dat, s, len);
659         c->str_dat[len] = 0;
660         c->next_atom = atom_table[hc];
661         atom_table[hc] = c;
662         atom_cnt++;
663         return c;
666 static struct branch *lookup_branch(const char *name)
668         unsigned int hc = hc_str(name, strlen(name)) % branch_table_sz;
669         struct branch *b;
671         for (b = branch_table[hc]; b; b = b->table_next_branch)
672                 if (!strcmp(name, b->name))
673                         return b;
674         return NULL;
677 static struct branch *new_branch(const char *name)
679         unsigned int hc = hc_str(name, strlen(name)) % branch_table_sz;
680         struct branch *b = lookup_branch(name);
682         if (b)
683                 die("Invalid attempt to create duplicate branch: %s", name);
684         switch (check_ref_format(name)) {
685         case 0: break; /* its valid */
686         case CHECK_REF_FORMAT_ONELEVEL:
687                 break; /* valid, but too few '/', allow anyway */
688         default:
689                 die("Branch name doesn't conform to GIT standards: %s", name);
690         }
692         b = pool_calloc(1, sizeof(struct branch));
693         b->name = pool_strdup(name);
694         b->table_next_branch = branch_table[hc];
695         b->branch_tree.versions[0].mode = S_IFDIR;
696         b->branch_tree.versions[1].mode = S_IFDIR;
697         b->active = 0;
698         b->pack_id = MAX_PACK_ID;
699         branch_table[hc] = b;
700         branch_count++;
701         return b;
704 static unsigned int hc_entries(unsigned int cnt)
706         cnt = cnt & 7 ? (cnt / 8) + 1 : cnt / 8;
707         return cnt < avail_tree_table_sz ? cnt : avail_tree_table_sz - 1;
710 static struct tree_content *new_tree_content(unsigned int cnt)
712         struct avail_tree_content *f, *l = NULL;
713         struct tree_content *t;
714         unsigned int hc = hc_entries(cnt);
716         for (f = avail_tree_table[hc]; f; l = f, f = f->next_avail)
717                 if (f->entry_capacity >= cnt)
718                         break;
720         if (f) {
721                 if (l)
722                         l->next_avail = f->next_avail;
723                 else
724                         avail_tree_table[hc] = f->next_avail;
725         } else {
726                 cnt = cnt & 7 ? ((cnt / 8) + 1) * 8 : cnt;
727                 f = pool_alloc(sizeof(*t) + sizeof(t->entries[0]) * cnt);
728                 f->entry_capacity = cnt;
729         }
731         t = (struct tree_content*)f;
732         t->entry_count = 0;
733         t->delta_depth = 0;
734         return t;
737 static void release_tree_entry(struct tree_entry *e);
738 static void release_tree_content(struct tree_content *t)
740         struct avail_tree_content *f = (struct avail_tree_content*)t;
741         unsigned int hc = hc_entries(f->entry_capacity);
742         f->next_avail = avail_tree_table[hc];
743         avail_tree_table[hc] = f;
746 static void release_tree_content_recursive(struct tree_content *t)
748         unsigned int i;
749         for (i = 0; i < t->entry_count; i++)
750                 release_tree_entry(t->entries[i]);
751         release_tree_content(t);
754 static struct tree_content *grow_tree_content(
755         struct tree_content *t,
756         int amt)
758         struct tree_content *r = new_tree_content(t->entry_count + amt);
759         r->entry_count = t->entry_count;
760         r->delta_depth = t->delta_depth;
761         memcpy(r->entries,t->entries,t->entry_count*sizeof(t->entries[0]));
762         release_tree_content(t);
763         return r;
766 static struct tree_entry *new_tree_entry(void)
768         struct tree_entry *e;
770         if (!avail_tree_entry) {
771                 unsigned int n = tree_entry_alloc;
772                 total_allocd += n * sizeof(struct tree_entry);
773                 avail_tree_entry = e = xmalloc(n * sizeof(struct tree_entry));
774                 while (n-- > 1) {
775                         *((void**)e) = e + 1;
776                         e++;
777                 }
778                 *((void**)e) = NULL;
779         }
781         e = avail_tree_entry;
782         avail_tree_entry = *((void**)e);
783         return e;
786 static void release_tree_entry(struct tree_entry *e)
788         if (e->tree)
789                 release_tree_content_recursive(e->tree);
790         *((void**)e) = avail_tree_entry;
791         avail_tree_entry = e;
794 static struct tree_content *dup_tree_content(struct tree_content *s)
796         struct tree_content *d;
797         struct tree_entry *a, *b;
798         unsigned int i;
800         if (!s)
801                 return NULL;
802         d = new_tree_content(s->entry_count);
803         for (i = 0; i < s->entry_count; i++) {
804                 a = s->entries[i];
805                 b = new_tree_entry();
806                 memcpy(b, a, sizeof(*a));
807                 if (a->tree && is_null_sha1(b->versions[1].sha1))
808                         b->tree = dup_tree_content(a->tree);
809                 else
810                         b->tree = NULL;
811                 d->entries[i] = b;
812         }
813         d->entry_count = s->entry_count;
814         d->delta_depth = s->delta_depth;
816         return d;
819 static void start_packfile(void)
821         static char tmpfile[PATH_MAX];
822         struct packed_git *p;
823         struct pack_header hdr;
824         int pack_fd;
826         pack_fd = odb_mkstemp(tmpfile, sizeof(tmpfile),
827                               "pack/tmp_pack_XXXXXX");
828         p = xcalloc(1, sizeof(*p) + strlen(tmpfile) + 2);
829         strcpy(p->pack_name, tmpfile);
830         p->pack_fd = pack_fd;
832         hdr.hdr_signature = htonl(PACK_SIGNATURE);
833         hdr.hdr_version = htonl(2);
834         hdr.hdr_entries = 0;
835         write_or_die(p->pack_fd, &hdr, sizeof(hdr));
837         pack_data = p;
838         pack_size = sizeof(hdr);
839         object_count = 0;
841         all_packs = xrealloc(all_packs, sizeof(*all_packs) * (pack_id + 1));
842         all_packs[pack_id] = p;
845 static int oecmp (const void *a_, const void *b_)
847         struct object_entry *a = *((struct object_entry**)a_);
848         struct object_entry *b = *((struct object_entry**)b_);
849         return hashcmp(a->sha1, b->sha1);
852 static char *create_index(void)
854         static char tmpfile[PATH_MAX];
855         git_SHA_CTX ctx;
856         struct sha1file *f;
857         struct object_entry **idx, **c, **last, *e;
858         struct object_entry_pool *o;
859         uint32_t array[256];
860         int i, idx_fd;
862         /* Build the sorted table of object IDs. */
863         idx = xmalloc(object_count * sizeof(struct object_entry*));
864         c = idx;
865         for (o = blocks; o; o = o->next_pool)
866                 for (e = o->next_free; e-- != o->entries;)
867                         if (pack_id == e->pack_id)
868                                 *c++ = e;
869         last = idx + object_count;
870         if (c != last)
871                 die("internal consistency error creating the index");
872         qsort(idx, object_count, sizeof(struct object_entry*), oecmp);
874         /* Generate the fan-out array. */
875         c = idx;
876         for (i = 0; i < 256; i++) {
877                 struct object_entry **next = c;
878                 while (next < last) {
879                         if ((*next)->sha1[0] != i)
880                                 break;
881                         next++;
882                 }
883                 array[i] = htonl(next - idx);
884                 c = next;
885         }
887         idx_fd = odb_mkstemp(tmpfile, sizeof(tmpfile),
888                              "pack/tmp_idx_XXXXXX");
889         f = sha1fd(idx_fd, tmpfile);
890         sha1write(f, array, 256 * sizeof(int));
891         git_SHA1_Init(&ctx);
892         for (c = idx; c != last; c++) {
893                 uint32_t offset = htonl((*c)->offset);
894                 sha1write(f, &offset, 4);
895                 sha1write(f, (*c)->sha1, sizeof((*c)->sha1));
896                 git_SHA1_Update(&ctx, (*c)->sha1, 20);
897         }
898         sha1write(f, pack_data->sha1, sizeof(pack_data->sha1));
899         sha1close(f, NULL, CSUM_FSYNC);
900         free(idx);
901         git_SHA1_Final(pack_data->sha1, &ctx);
902         return tmpfile;
905 static char *keep_pack(char *curr_index_name)
907         static char name[PATH_MAX];
908         static const char *keep_msg = "fast-import";
909         int keep_fd;
911         keep_fd = odb_pack_keep(name, sizeof(name), pack_data->sha1);
912         if (keep_fd < 0)
913                 die_errno("cannot create keep file");
914         write_or_die(keep_fd, keep_msg, strlen(keep_msg));
915         if (close(keep_fd))
916                 die_errno("failed to write keep file");
918         snprintf(name, sizeof(name), "%s/pack/pack-%s.pack",
919                  get_object_directory(), sha1_to_hex(pack_data->sha1));
920         if (move_temp_to_file(pack_data->pack_name, name))
921                 die("cannot store pack file");
923         snprintf(name, sizeof(name), "%s/pack/pack-%s.idx",
924                  get_object_directory(), sha1_to_hex(pack_data->sha1));
925         if (move_temp_to_file(curr_index_name, name))
926                 die("cannot store index file");
927         return name;
930 static void unkeep_all_packs(void)
932         static char name[PATH_MAX];
933         int k;
935         for (k = 0; k < pack_id; k++) {
936                 struct packed_git *p = all_packs[k];
937                 snprintf(name, sizeof(name), "%s/pack/pack-%s.keep",
938                          get_object_directory(), sha1_to_hex(p->sha1));
939                 unlink_or_warn(name);
940         }
943 static void end_packfile(void)
945         struct packed_git *old_p = pack_data, *new_p;
947         clear_delta_base_cache();
948         if (object_count) {
949                 char *idx_name;
950                 int i;
951                 struct branch *b;
952                 struct tag *t;
954                 close_pack_windows(pack_data);
955                 fixup_pack_header_footer(pack_data->pack_fd, pack_data->sha1,
956                                     pack_data->pack_name, object_count,
957                                     NULL, 0);
958                 close(pack_data->pack_fd);
959                 idx_name = keep_pack(create_index());
961                 /* Register the packfile with core git's machinery. */
962                 new_p = add_packed_git(idx_name, strlen(idx_name), 1);
963                 if (!new_p)
964                         die("core git rejected index %s", idx_name);
965                 all_packs[pack_id] = new_p;
966                 install_packed_git(new_p);
968                 /* Print the boundary */
969                 if (pack_edges) {
970                         fprintf(pack_edges, "%s:", new_p->pack_name);
971                         for (i = 0; i < branch_table_sz; i++) {
972                                 for (b = branch_table[i]; b; b = b->table_next_branch) {
973                                         if (b->pack_id == pack_id)
974                                                 fprintf(pack_edges, " %s", sha1_to_hex(b->sha1));
975                                 }
976                         }
977                         for (t = first_tag; t; t = t->next_tag) {
978                                 if (t->pack_id == pack_id)
979                                         fprintf(pack_edges, " %s", sha1_to_hex(t->sha1));
980                         }
981                         fputc('\n', pack_edges);
982                         fflush(pack_edges);
983                 }
985                 pack_id++;
986         }
987         else {
988                 close(old_p->pack_fd);
989                 unlink_or_warn(old_p->pack_name);
990         }
991         free(old_p);
993         /* We can't carry a delta across packfiles. */
994         strbuf_release(&last_blob.data);
995         last_blob.offset = 0;
996         last_blob.depth = 0;
999 static void cycle_packfile(void)
1001         end_packfile();
1002         start_packfile();
1005 static size_t encode_header(
1006         enum object_type type,
1007         uintmax_t size,
1008         unsigned char *hdr)
1010         int n = 1;
1011         unsigned char c;
1013         if (type < OBJ_COMMIT || type > OBJ_REF_DELTA)
1014                 die("bad type %d", type);
1016         c = (type << 4) | (size & 15);
1017         size >>= 4;
1018         while (size) {
1019                 *hdr++ = c | 0x80;
1020                 c = size & 0x7f;
1021                 size >>= 7;
1022                 n++;
1023         }
1024         *hdr = c;
1025         return n;
1028 static int store_object(
1029         enum object_type type,
1030         struct strbuf *dat,
1031         struct last_object *last,
1032         unsigned char *sha1out,
1033         uintmax_t mark)
1035         void *out, *delta;
1036         struct object_entry *e;
1037         unsigned char hdr[96];
1038         unsigned char sha1[20];
1039         unsigned long hdrlen, deltalen;
1040         git_SHA_CTX c;
1041         z_stream s;
1043         hdrlen = sprintf((char *)hdr,"%s %lu", typename(type),
1044                 (unsigned long)dat->len) + 1;
1045         git_SHA1_Init(&c);
1046         git_SHA1_Update(&c, hdr, hdrlen);
1047         git_SHA1_Update(&c, dat->buf, dat->len);
1048         git_SHA1_Final(sha1, &c);
1049         if (sha1out)
1050                 hashcpy(sha1out, sha1);
1052         e = insert_object(sha1);
1053         if (mark)
1054                 insert_mark(mark, e);
1055         if (e->offset) {
1056                 duplicate_count_by_type[type]++;
1057                 return 1;
1058         } else if (find_sha1_pack(sha1, packed_git)) {
1059                 e->type = type;
1060                 e->pack_id = MAX_PACK_ID;
1061                 e->offset = 1; /* just not zero! */
1062                 duplicate_count_by_type[type]++;
1063                 return 1;
1064         }
1066         if (last && last->data.buf && last->depth < max_depth) {
1067                 delta = diff_delta(last->data.buf, last->data.len,
1068                         dat->buf, dat->len,
1069                         &deltalen, 0);
1070                 if (delta && deltalen >= dat->len) {
1071                         free(delta);
1072                         delta = NULL;
1073                 }
1074         } else
1075                 delta = NULL;
1077         memset(&s, 0, sizeof(s));
1078         deflateInit(&s, pack_compression_level);
1079         if (delta) {
1080                 s.next_in = delta;
1081                 s.avail_in = deltalen;
1082         } else {
1083                 s.next_in = (void *)dat->buf;
1084                 s.avail_in = dat->len;
1085         }
1086         s.avail_out = deflateBound(&s, s.avail_in);
1087         s.next_out = out = xmalloc(s.avail_out);
1088         while (deflate(&s, Z_FINISH) == Z_OK)
1089                 /* nothing */;
1090         deflateEnd(&s);
1092         /* Determine if we should auto-checkpoint. */
1093         if ((pack_size + 60 + s.total_out) > max_packsize
1094                 || (pack_size + 60 + s.total_out) < pack_size) {
1096                 /* This new object needs to *not* have the current pack_id. */
1097                 e->pack_id = pack_id + 1;
1098                 cycle_packfile();
1100                 /* We cannot carry a delta into the new pack. */
1101                 if (delta) {
1102                         free(delta);
1103                         delta = NULL;
1105                         memset(&s, 0, sizeof(s));
1106                         deflateInit(&s, pack_compression_level);
1107                         s.next_in = (void *)dat->buf;
1108                         s.avail_in = dat->len;
1109                         s.avail_out = deflateBound(&s, s.avail_in);
1110                         s.next_out = out = xrealloc(out, s.avail_out);
1111                         while (deflate(&s, Z_FINISH) == Z_OK)
1112                                 /* nothing */;
1113                         deflateEnd(&s);
1114                 }
1115         }
1117         e->type = type;
1118         e->pack_id = pack_id;
1119         e->offset = pack_size;
1120         object_count++;
1121         object_count_by_type[type]++;
1123         if (delta) {
1124                 unsigned long ofs = e->offset - last->offset;
1125                 unsigned pos = sizeof(hdr) - 1;
1127                 delta_count_by_type[type]++;
1128                 e->depth = last->depth + 1;
1130                 hdrlen = encode_header(OBJ_OFS_DELTA, deltalen, hdr);
1131                 write_or_die(pack_data->pack_fd, hdr, hdrlen);
1132                 pack_size += hdrlen;
1134                 hdr[pos] = ofs & 127;
1135                 while (ofs >>= 7)
1136                         hdr[--pos] = 128 | (--ofs & 127);
1137                 write_or_die(pack_data->pack_fd, hdr + pos, sizeof(hdr) - pos);
1138                 pack_size += sizeof(hdr) - pos;
1139         } else {
1140                 e->depth = 0;
1141                 hdrlen = encode_header(type, dat->len, hdr);
1142                 write_or_die(pack_data->pack_fd, hdr, hdrlen);
1143                 pack_size += hdrlen;
1144         }
1146         write_or_die(pack_data->pack_fd, out, s.total_out);
1147         pack_size += s.total_out;
1149         free(out);
1150         free(delta);
1151         if (last) {
1152                 if (last->no_swap) {
1153                         last->data = *dat;
1154                 } else {
1155                         strbuf_swap(&last->data, dat);
1156                 }
1157                 last->offset = e->offset;
1158                 last->depth = e->depth;
1159         }
1160         return 0;
1163 static void truncate_pack(off_t to)
1165         if (ftruncate(pack_data->pack_fd, to)
1166          || lseek(pack_data->pack_fd, to, SEEK_SET) != to)
1167                 die_errno("cannot truncate pack to skip duplicate");
1168         pack_size = to;
1171 static void stream_blob(uintmax_t len, unsigned char *sha1out, uintmax_t mark)
1173         size_t in_sz = 64 * 1024, out_sz = 64 * 1024;
1174         unsigned char *in_buf = xmalloc(in_sz);
1175         unsigned char *out_buf = xmalloc(out_sz);
1176         struct object_entry *e;
1177         unsigned char sha1[20];
1178         unsigned long hdrlen;
1179         off_t offset;
1180         git_SHA_CTX c;
1181         z_stream s;
1182         int status = Z_OK;
1184         /* Determine if we should auto-checkpoint. */
1185         if ((pack_size + 60 + len) > max_packsize
1186                 || (pack_size + 60 + len) < pack_size)
1187                 cycle_packfile();
1189         offset = pack_size;
1191         hdrlen = snprintf((char *)out_buf, out_sz, "blob %" PRIuMAX, len) + 1;
1192         if (out_sz <= hdrlen)
1193                 die("impossibly large object header");
1195         git_SHA1_Init(&c);
1196         git_SHA1_Update(&c, out_buf, hdrlen);
1198         memset(&s, 0, sizeof(s));
1199         deflateInit(&s, pack_compression_level);
1201         hdrlen = encode_header(OBJ_BLOB, len, out_buf);
1202         if (out_sz <= hdrlen)
1203                 die("impossibly large object header");
1205         s.next_out = out_buf + hdrlen;
1206         s.avail_out = out_sz - hdrlen;
1208         while (status != Z_STREAM_END) {
1209                 if (0 < len && !s.avail_in) {
1210                         size_t cnt = in_sz < len ? in_sz : (size_t)len;
1211                         size_t n = fread(in_buf, 1, cnt, stdin);
1212                         if (!n && feof(stdin))
1213                                 die("EOF in data (%" PRIuMAX " bytes remaining)", len);
1215                         git_SHA1_Update(&c, in_buf, n);
1216                         s.next_in = in_buf;
1217                         s.avail_in = n;
1218                         len -= n;
1219                 }
1221                 status = deflate(&s, len ? 0 : Z_FINISH);
1223                 if (!s.avail_out || status == Z_STREAM_END) {
1224                         size_t n = s.next_out - out_buf;
1225                         write_or_die(pack_data->pack_fd, out_buf, n);
1226                         pack_size += n;
1227                         s.next_out = out_buf;
1228                         s.avail_out = out_sz;
1229                 }
1231                 switch (status) {
1232                 case Z_OK:
1233                 case Z_BUF_ERROR:
1234                 case Z_STREAM_END:
1235                         continue;
1236                 default:
1237                         die("unexpected deflate failure: %d", status);
1238                 }
1239         }
1240         deflateEnd(&s);
1241         git_SHA1_Final(sha1, &c);
1243         if (sha1out)
1244                 hashcpy(sha1out, sha1);
1246         e = insert_object(sha1);
1248         if (mark)
1249                 insert_mark(mark, e);
1251         if (e->offset) {
1252                 duplicate_count_by_type[OBJ_BLOB]++;
1253                 truncate_pack(offset);
1255         } else if (find_sha1_pack(sha1, packed_git)) {
1256                 e->type = OBJ_BLOB;
1257                 e->pack_id = MAX_PACK_ID;
1258                 e->offset = 1; /* just not zero! */
1259                 duplicate_count_by_type[OBJ_BLOB]++;
1260                 truncate_pack(offset);
1262         } else {
1263                 e->depth = 0;
1264                 e->type = OBJ_BLOB;
1265                 e->pack_id = pack_id;
1266                 e->offset = offset;
1267                 object_count++;
1268                 object_count_by_type[OBJ_BLOB]++;
1269         }
1271         free(in_buf);
1272         free(out_buf);
1275 /* All calls must be guarded by find_object() or find_mark() to
1276  * ensure the 'struct object_entry' passed was written by this
1277  * process instance.  We unpack the entry by the offset, avoiding
1278  * the need for the corresponding .idx file.  This unpacking rule
1279  * works because we only use OBJ_REF_DELTA within the packfiles
1280  * created by fast-import.
1281  *
1282  * oe must not be NULL.  Such an oe usually comes from giving
1283  * an unknown SHA-1 to find_object() or an undefined mark to
1284  * find_mark().  Callers must test for this condition and use
1285  * the standard read_sha1_file() when it happens.
1286  *
1287  * oe->pack_id must not be MAX_PACK_ID.  Such an oe is usually from
1288  * find_mark(), where the mark was reloaded from an existing marks
1289  * file and is referencing an object that this fast-import process
1290  * instance did not write out to a packfile.  Callers must test for
1291  * this condition and use read_sha1_file() instead.
1292  */
1293 static void *gfi_unpack_entry(
1294         struct object_entry *oe,
1295         unsigned long *sizep)
1297         enum object_type type;
1298         struct packed_git *p = all_packs[oe->pack_id];
1299         if (p == pack_data && p->pack_size < (pack_size + 20)) {
1300                 /* The object is stored in the packfile we are writing to
1301                  * and we have modified it since the last time we scanned
1302                  * back to read a previously written object.  If an old
1303                  * window covered [p->pack_size, p->pack_size + 20) its
1304                  * data is stale and is not valid.  Closing all windows
1305                  * and updating the packfile length ensures we can read
1306                  * the newly written data.
1307                  */
1308                 close_pack_windows(p);
1310                 /* We have to offer 20 bytes additional on the end of
1311                  * the packfile as the core unpacker code assumes the
1312                  * footer is present at the file end and must promise
1313                  * at least 20 bytes within any window it maps.  But
1314                  * we don't actually create the footer here.
1315                  */
1316                 p->pack_size = pack_size + 20;
1317         }
1318         return unpack_entry(p, oe->offset, &type, sizep);
1321 static const char *get_mode(const char *str, uint16_t *modep)
1323         unsigned char c;
1324         uint16_t mode = 0;
1326         while ((c = *str++) != ' ') {
1327                 if (c < '0' || c > '7')
1328                         return NULL;
1329                 mode = (mode << 3) + (c - '0');
1330         }
1331         *modep = mode;
1332         return str;
1335 static void load_tree(struct tree_entry *root)
1337         unsigned char *sha1 = root->versions[1].sha1;
1338         struct object_entry *myoe;
1339         struct tree_content *t;
1340         unsigned long size;
1341         char *buf;
1342         const char *c;
1344         root->tree = t = new_tree_content(8);
1345         if (is_null_sha1(sha1))
1346                 return;
1348         myoe = find_object(sha1);
1349         if (myoe && myoe->pack_id != MAX_PACK_ID) {
1350                 if (myoe->type != OBJ_TREE)
1351                         die("Not a tree: %s", sha1_to_hex(sha1));
1352                 t->delta_depth = myoe->depth;
1353                 buf = gfi_unpack_entry(myoe, &size);
1354                 if (!buf)
1355                         die("Can't load tree %s", sha1_to_hex(sha1));
1356         } else {
1357                 enum object_type type;
1358                 buf = read_sha1_file(sha1, &type, &size);
1359                 if (!buf || type != OBJ_TREE)
1360                         die("Can't load tree %s", sha1_to_hex(sha1));
1361         }
1363         c = buf;
1364         while (c != (buf + size)) {
1365                 struct tree_entry *e = new_tree_entry();
1367                 if (t->entry_count == t->entry_capacity)
1368                         root->tree = t = grow_tree_content(t, t->entry_count);
1369                 t->entries[t->entry_count++] = e;
1371                 e->tree = NULL;
1372                 c = get_mode(c, &e->versions[1].mode);
1373                 if (!c)
1374                         die("Corrupt mode in %s", sha1_to_hex(sha1));
1375                 e->versions[0].mode = e->versions[1].mode;
1376                 e->name = to_atom(c, strlen(c));
1377                 c += e->name->str_len + 1;
1378                 hashcpy(e->versions[0].sha1, (unsigned char *)c);
1379                 hashcpy(e->versions[1].sha1, (unsigned char *)c);
1380                 c += 20;
1381         }
1382         free(buf);
1385 static int tecmp0 (const void *_a, const void *_b)
1387         struct tree_entry *a = *((struct tree_entry**)_a);
1388         struct tree_entry *b = *((struct tree_entry**)_b);
1389         return base_name_compare(
1390                 a->name->str_dat, a->name->str_len, a->versions[0].mode,
1391                 b->name->str_dat, b->name->str_len, b->versions[0].mode);
1394 static int tecmp1 (const void *_a, const void *_b)
1396         struct tree_entry *a = *((struct tree_entry**)_a);
1397         struct tree_entry *b = *((struct tree_entry**)_b);
1398         return base_name_compare(
1399                 a->name->str_dat, a->name->str_len, a->versions[1].mode,
1400                 b->name->str_dat, b->name->str_len, b->versions[1].mode);
1403 static void mktree(struct tree_content *t, int v, struct strbuf *b)
1405         size_t maxlen = 0;
1406         unsigned int i;
1408         if (!v)
1409                 qsort(t->entries,t->entry_count,sizeof(t->entries[0]),tecmp0);
1410         else
1411                 qsort(t->entries,t->entry_count,sizeof(t->entries[0]),tecmp1);
1413         for (i = 0; i < t->entry_count; i++) {
1414                 if (t->entries[i]->versions[v].mode)
1415                         maxlen += t->entries[i]->name->str_len + 34;
1416         }
1418         strbuf_reset(b);
1419         strbuf_grow(b, maxlen);
1420         for (i = 0; i < t->entry_count; i++) {
1421                 struct tree_entry *e = t->entries[i];
1422                 if (!e->versions[v].mode)
1423                         continue;
1424                 strbuf_addf(b, "%o %s%c", (unsigned int)e->versions[v].mode,
1425                                         e->name->str_dat, '\0');
1426                 strbuf_add(b, e->versions[v].sha1, 20);
1427         }
1430 static void store_tree(struct tree_entry *root)
1432         struct tree_content *t = root->tree;
1433         unsigned int i, j, del;
1434         struct last_object lo = { STRBUF_INIT, 0, 0, /* no_swap */ 1 };
1435         struct object_entry *le;
1437         if (!is_null_sha1(root->versions[1].sha1))
1438                 return;
1440         for (i = 0; i < t->entry_count; i++) {
1441                 if (t->entries[i]->tree)
1442                         store_tree(t->entries[i]);
1443         }
1445         le = find_object(root->versions[0].sha1);
1446         if (S_ISDIR(root->versions[0].mode) && le && le->pack_id == pack_id) {
1447                 mktree(t, 0, &old_tree);
1448                 lo.data = old_tree;
1449                 lo.offset = le->offset;
1450                 lo.depth = t->delta_depth;
1451         }
1453         mktree(t, 1, &new_tree);
1454         store_object(OBJ_TREE, &new_tree, &lo, root->versions[1].sha1, 0);
1456         t->delta_depth = lo.depth;
1457         for (i = 0, j = 0, del = 0; i < t->entry_count; i++) {
1458                 struct tree_entry *e = t->entries[i];
1459                 if (e->versions[1].mode) {
1460                         e->versions[0].mode = e->versions[1].mode;
1461                         hashcpy(e->versions[0].sha1, e->versions[1].sha1);
1462                         t->entries[j++] = e;
1463                 } else {
1464                         release_tree_entry(e);
1465                         del++;
1466                 }
1467         }
1468         t->entry_count -= del;
1471 static int tree_content_set(
1472         struct tree_entry *root,
1473         const char *p,
1474         const unsigned char *sha1,
1475         const uint16_t mode,
1476         struct tree_content *subtree)
1478         struct tree_content *t = root->tree;
1479         const char *slash1;
1480         unsigned int i, n;
1481         struct tree_entry *e;
1483         slash1 = strchr(p, '/');
1484         if (slash1)
1485                 n = slash1 - p;
1486         else
1487                 n = strlen(p);
1488         if (!n)
1489                 die("Empty path component found in input");
1490         if (!slash1 && !S_ISDIR(mode) && subtree)
1491                 die("Non-directories cannot have subtrees");
1493         for (i = 0; i < t->entry_count; i++) {
1494                 e = t->entries[i];
1495                 if (e->name->str_len == n && !strncmp(p, e->name->str_dat, n)) {
1496                         if (!slash1) {
1497                                 if (!S_ISDIR(mode)
1498                                                 && e->versions[1].mode == mode
1499                                                 && !hashcmp(e->versions[1].sha1, sha1))
1500                                         return 0;
1501                                 e->versions[1].mode = mode;
1502                                 hashcpy(e->versions[1].sha1, sha1);
1503                                 if (e->tree)
1504                                         release_tree_content_recursive(e->tree);
1505                                 e->tree = subtree;
1506                                 hashclr(root->versions[1].sha1);
1507                                 return 1;
1508                         }
1509                         if (!S_ISDIR(e->versions[1].mode)) {
1510                                 e->tree = new_tree_content(8);
1511                                 e->versions[1].mode = S_IFDIR;
1512                         }
1513                         if (!e->tree)
1514                                 load_tree(e);
1515                         if (tree_content_set(e, slash1 + 1, sha1, mode, subtree)) {
1516                                 hashclr(root->versions[1].sha1);
1517                                 return 1;
1518                         }
1519                         return 0;
1520                 }
1521         }
1523         if (t->entry_count == t->entry_capacity)
1524                 root->tree = t = grow_tree_content(t, t->entry_count);
1525         e = new_tree_entry();
1526         e->name = to_atom(p, n);
1527         e->versions[0].mode = 0;
1528         hashclr(e->versions[0].sha1);
1529         t->entries[t->entry_count++] = e;
1530         if (slash1) {
1531                 e->tree = new_tree_content(8);
1532                 e->versions[1].mode = S_IFDIR;
1533                 tree_content_set(e, slash1 + 1, sha1, mode, subtree);
1534         } else {
1535                 e->tree = subtree;
1536                 e->versions[1].mode = mode;
1537                 hashcpy(e->versions[1].sha1, sha1);
1538         }
1539         hashclr(root->versions[1].sha1);
1540         return 1;
1543 static int tree_content_remove(
1544         struct tree_entry *root,
1545         const char *p,
1546         struct tree_entry *backup_leaf)
1548         struct tree_content *t = root->tree;
1549         const char *slash1;
1550         unsigned int i, n;
1551         struct tree_entry *e;
1553         slash1 = strchr(p, '/');
1554         if (slash1)
1555                 n = slash1 - p;
1556         else
1557                 n = strlen(p);
1559         for (i = 0; i < t->entry_count; i++) {
1560                 e = t->entries[i];
1561                 if (e->name->str_len == n && !strncmp(p, e->name->str_dat, n)) {
1562                         if (!slash1 || !S_ISDIR(e->versions[1].mode))
1563                                 goto del_entry;
1564                         if (!e->tree)
1565                                 load_tree(e);
1566                         if (tree_content_remove(e, slash1 + 1, backup_leaf)) {
1567                                 for (n = 0; n < e->tree->entry_count; n++) {
1568                                         if (e->tree->entries[n]->versions[1].mode) {
1569                                                 hashclr(root->versions[1].sha1);
1570                                                 return 1;
1571                                         }
1572                                 }
1573                                 backup_leaf = NULL;
1574                                 goto del_entry;
1575                         }
1576                         return 0;
1577                 }
1578         }
1579         return 0;
1581 del_entry:
1582         if (backup_leaf)
1583                 memcpy(backup_leaf, e, sizeof(*backup_leaf));
1584         else if (e->tree)
1585                 release_tree_content_recursive(e->tree);
1586         e->tree = NULL;
1587         e->versions[1].mode = 0;
1588         hashclr(e->versions[1].sha1);
1589         hashclr(root->versions[1].sha1);
1590         return 1;
1593 static int tree_content_get(
1594         struct tree_entry *root,
1595         const char *p,
1596         struct tree_entry *leaf)
1598         struct tree_content *t = root->tree;
1599         const char *slash1;
1600         unsigned int i, n;
1601         struct tree_entry *e;
1603         slash1 = strchr(p, '/');
1604         if (slash1)
1605                 n = slash1 - p;
1606         else
1607                 n = strlen(p);
1609         for (i = 0; i < t->entry_count; i++) {
1610                 e = t->entries[i];
1611                 if (e->name->str_len == n && !strncmp(p, e->name->str_dat, n)) {
1612                         if (!slash1) {
1613                                 memcpy(leaf, e, sizeof(*leaf));
1614                                 if (e->tree && is_null_sha1(e->versions[1].sha1))
1615                                         leaf->tree = dup_tree_content(e->tree);
1616                                 else
1617                                         leaf->tree = NULL;
1618                                 return 1;
1619                         }
1620                         if (!S_ISDIR(e->versions[1].mode))
1621                                 return 0;
1622                         if (!e->tree)
1623                                 load_tree(e);
1624                         return tree_content_get(e, slash1 + 1, leaf);
1625                 }
1626         }
1627         return 0;
1630 static int update_branch(struct branch *b)
1632         static const char *msg = "fast-import";
1633         struct ref_lock *lock;
1634         unsigned char old_sha1[20];
1636         if (is_null_sha1(b->sha1))
1637                 return 0;
1638         if (read_ref(b->name, old_sha1))
1639                 hashclr(old_sha1);
1640         lock = lock_any_ref_for_update(b->name, old_sha1, 0);
1641         if (!lock)
1642                 return error("Unable to lock %s", b->name);
1643         if (!force_update && !is_null_sha1(old_sha1)) {
1644                 struct commit *old_cmit, *new_cmit;
1646                 old_cmit = lookup_commit_reference_gently(old_sha1, 0);
1647                 new_cmit = lookup_commit_reference_gently(b->sha1, 0);
1648                 if (!old_cmit || !new_cmit) {
1649                         unlock_ref(lock);
1650                         return error("Branch %s is missing commits.", b->name);
1651                 }
1653                 if (!in_merge_bases(old_cmit, &new_cmit, 1)) {
1654                         unlock_ref(lock);
1655                         warning("Not updating %s"
1656                                 " (new tip %s does not contain %s)",
1657                                 b->name, sha1_to_hex(b->sha1), sha1_to_hex(old_sha1));
1658                         return -1;
1659                 }
1660         }
1661         if (write_ref_sha1(lock, b->sha1, msg) < 0)
1662                 return error("Unable to update %s", b->name);
1663         return 0;
1666 static void dump_branches(void)
1668         unsigned int i;
1669         struct branch *b;
1671         for (i = 0; i < branch_table_sz; i++) {
1672                 for (b = branch_table[i]; b; b = b->table_next_branch)
1673                         failure |= update_branch(b);
1674         }
1677 static void dump_tags(void)
1679         static const char *msg = "fast-import";
1680         struct tag *t;
1681         struct ref_lock *lock;
1682         char ref_name[PATH_MAX];
1684         for (t = first_tag; t; t = t->next_tag) {
1685                 sprintf(ref_name, "tags/%s", t->name);
1686                 lock = lock_ref_sha1(ref_name, NULL);
1687                 if (!lock || write_ref_sha1(lock, t->sha1, msg) < 0)
1688                         failure |= error("Unable to update %s", ref_name);
1689         }
1692 static void dump_marks_helper(FILE *f,
1693         uintmax_t base,
1694         struct mark_set *m)
1696         uintmax_t k;
1697         if (m->shift) {
1698                 for (k = 0; k < 1024; k++) {
1699                         if (m->data.sets[k])
1700                                 dump_marks_helper(f, (base + k) << m->shift,
1701                                         m->data.sets[k]);
1702                 }
1703         } else {
1704                 for (k = 0; k < 1024; k++) {
1705                         if (m->data.marked[k])
1706                                 fprintf(f, ":%" PRIuMAX " %s\n", base + k,
1707                                         sha1_to_hex(m->data.marked[k]->sha1));
1708                 }
1709         }
1712 static void dump_marks(void)
1714         static struct lock_file mark_lock;
1715         int mark_fd;
1716         FILE *f;
1718         if (!mark_file)
1719                 return;
1721         mark_fd = hold_lock_file_for_update(&mark_lock, mark_file, 0);
1722         if (mark_fd < 0) {
1723                 failure |= error("Unable to write marks file %s: %s",
1724                         mark_file, strerror(errno));
1725                 return;
1726         }
1728         f = fdopen(mark_fd, "w");
1729         if (!f) {
1730                 int saved_errno = errno;
1731                 rollback_lock_file(&mark_lock);
1732                 failure |= error("Unable to write marks file %s: %s",
1733                         mark_file, strerror(saved_errno));
1734                 return;
1735         }
1737         /*
1738          * Since the lock file was fdopen()'ed, it should not be close()'ed.
1739          * Assign -1 to the lock file descriptor so that commit_lock_file()
1740          * won't try to close() it.
1741          */
1742         mark_lock.fd = -1;
1744         dump_marks_helper(f, 0, marks);
1745         if (ferror(f) || fclose(f)) {
1746                 int saved_errno = errno;
1747                 rollback_lock_file(&mark_lock);
1748                 failure |= error("Unable to write marks file %s: %s",
1749                         mark_file, strerror(saved_errno));
1750                 return;
1751         }
1753         if (commit_lock_file(&mark_lock)) {
1754                 int saved_errno = errno;
1755                 rollback_lock_file(&mark_lock);
1756                 failure |= error("Unable to commit marks file %s: %s",
1757                         mark_file, strerror(saved_errno));
1758                 return;
1759         }
1762 static int read_next_command(void)
1764         static int stdin_eof = 0;
1766         if (stdin_eof) {
1767                 unread_command_buf = 0;
1768                 return EOF;
1769         }
1771         do {
1772                 if (unread_command_buf) {
1773                         unread_command_buf = 0;
1774                 } else {
1775                         struct recent_command *rc;
1777                         strbuf_detach(&command_buf, NULL);
1778                         stdin_eof = strbuf_getline(&command_buf, stdin, '\n');
1779                         if (stdin_eof)
1780                                 return EOF;
1782                         rc = rc_free;
1783                         if (rc)
1784                                 rc_free = rc->next;
1785                         else {
1786                                 rc = cmd_hist.next;
1787                                 cmd_hist.next = rc->next;
1788                                 cmd_hist.next->prev = &cmd_hist;
1789                                 free(rc->buf);
1790                         }
1792                         rc->buf = command_buf.buf;
1793                         rc->prev = cmd_tail;
1794                         rc->next = cmd_hist.prev;
1795                         rc->prev->next = rc;
1796                         cmd_tail = rc;
1797                 }
1798         } while (command_buf.buf[0] == '#');
1800         return 0;
1803 static void skip_optional_lf(void)
1805         int term_char = fgetc(stdin);
1806         if (term_char != '\n' && term_char != EOF)
1807                 ungetc(term_char, stdin);
1810 static void parse_mark(void)
1812         if (!prefixcmp(command_buf.buf, "mark :")) {
1813                 next_mark = strtoumax(command_buf.buf + 6, NULL, 10);
1814                 read_next_command();
1815         }
1816         else
1817                 next_mark = 0;
1820 static int parse_data(struct strbuf *sb, uintmax_t limit, uintmax_t *len_res)
1822         strbuf_reset(sb);
1824         if (prefixcmp(command_buf.buf, "data "))
1825                 die("Expected 'data n' command, found: %s", command_buf.buf);
1827         if (!prefixcmp(command_buf.buf + 5, "<<")) {
1828                 char *term = xstrdup(command_buf.buf + 5 + 2);
1829                 size_t term_len = command_buf.len - 5 - 2;
1831                 strbuf_detach(&command_buf, NULL);
1832                 for (;;) {
1833                         if (strbuf_getline(&command_buf, stdin, '\n') == EOF)
1834                                 die("EOF in data (terminator '%s' not found)", term);
1835                         if (term_len == command_buf.len
1836                                 && !strcmp(term, command_buf.buf))
1837                                 break;
1838                         strbuf_addbuf(sb, &command_buf);
1839                         strbuf_addch(sb, '\n');
1840                 }
1841                 free(term);
1842         }
1843         else {
1844                 uintmax_t len = strtoumax(command_buf.buf + 5, NULL, 10);
1845                 size_t n = 0, length = (size_t)len;
1847                 if (limit && limit < len) {
1848                         *len_res = len;
1849                         return 0;
1850                 }
1851                 if (length < len)
1852                         die("data is too large to use in this context");
1854                 while (n < length) {
1855                         size_t s = strbuf_fread(sb, length - n, stdin);
1856                         if (!s && feof(stdin))
1857                                 die("EOF in data (%lu bytes remaining)",
1858                                         (unsigned long)(length - n));
1859                         n += s;
1860                 }
1861         }
1863         skip_optional_lf();
1864         return 1;
1867 static int validate_raw_date(const char *src, char *result, int maxlen)
1869         const char *orig_src = src;
1870         char *endp;
1871         unsigned long num;
1873         errno = 0;
1875         num = strtoul(src, &endp, 10);
1876         /* NEEDSWORK: perhaps check for reasonable values? */
1877         if (errno || endp == src || *endp != ' ')
1878                 return -1;
1880         src = endp + 1;
1881         if (*src != '-' && *src != '+')
1882                 return -1;
1884         num = strtoul(src + 1, &endp, 10);
1885         if (errno || endp == src + 1 || *endp || (endp - orig_src) >= maxlen ||
1886             1400 < num)
1887                 return -1;
1889         strcpy(result, orig_src);
1890         return 0;
1893 static char *parse_ident(const char *buf)
1895         const char *gt;
1896         size_t name_len;
1897         char *ident;
1899         gt = strrchr(buf, '>');
1900         if (!gt)
1901                 die("Missing > in ident string: %s", buf);
1902         gt++;
1903         if (*gt != ' ')
1904                 die("Missing space after > in ident string: %s", buf);
1905         gt++;
1906         name_len = gt - buf;
1907         ident = xmalloc(name_len + 24);
1908         strncpy(ident, buf, name_len);
1910         switch (whenspec) {
1911         case WHENSPEC_RAW:
1912                 if (validate_raw_date(gt, ident + name_len, 24) < 0)
1913                         die("Invalid raw date \"%s\" in ident: %s", gt, buf);
1914                 break;
1915         case WHENSPEC_RFC2822:
1916                 if (parse_date(gt, ident + name_len, 24) < 0)
1917                         die("Invalid rfc2822 date \"%s\" in ident: %s", gt, buf);
1918                 break;
1919         case WHENSPEC_NOW:
1920                 if (strcmp("now", gt))
1921                         die("Date in ident must be 'now': %s", buf);
1922                 datestamp(ident + name_len, 24);
1923                 break;
1924         }
1926         return ident;
1929 static void parse_and_store_blob(
1930         struct last_object *last,
1931         unsigned char *sha1out,
1932         uintmax_t mark)
1934         static struct strbuf buf = STRBUF_INIT;
1935         uintmax_t len;
1937         if (parse_data(&buf, big_file_threshold, &len))
1938                 store_object(OBJ_BLOB, &buf, last, sha1out, mark);
1939         else {
1940                 if (last) {
1941                         strbuf_release(&last->data);
1942                         last->offset = 0;
1943                         last->depth = 0;
1944                 }
1945                 stream_blob(len, sha1out, mark);
1946                 skip_optional_lf();
1947         }
1950 static void parse_new_blob(void)
1952         read_next_command();
1953         parse_mark();
1954         parse_and_store_blob(&last_blob, NULL, next_mark);
1957 static void unload_one_branch(void)
1959         while (cur_active_branches
1960                 && cur_active_branches >= max_active_branches) {
1961                 uintmax_t min_commit = ULONG_MAX;
1962                 struct branch *e, *l = NULL, *p = NULL;
1964                 for (e = active_branches; e; e = e->active_next_branch) {
1965                         if (e->last_commit < min_commit) {
1966                                 p = l;
1967                                 min_commit = e->last_commit;
1968                         }
1969                         l = e;
1970                 }
1972                 if (p) {
1973                         e = p->active_next_branch;
1974                         p->active_next_branch = e->active_next_branch;
1975                 } else {
1976                         e = active_branches;
1977                         active_branches = e->active_next_branch;
1978                 }
1979                 e->active = 0;
1980                 e->active_next_branch = NULL;
1981                 if (e->branch_tree.tree) {
1982                         release_tree_content_recursive(e->branch_tree.tree);
1983                         e->branch_tree.tree = NULL;
1984                 }
1985                 cur_active_branches--;
1986         }
1989 static void load_branch(struct branch *b)
1991         load_tree(&b->branch_tree);
1992         if (!b->active) {
1993                 b->active = 1;
1994                 b->active_next_branch = active_branches;
1995                 active_branches = b;
1996                 cur_active_branches++;
1997                 branch_load_count++;
1998         }
2001 static void file_change_m(struct branch *b)
2003         const char *p = command_buf.buf + 2;
2004         static struct strbuf uq = STRBUF_INIT;
2005         const char *endp;
2006         struct object_entry *oe = oe;
2007         unsigned char sha1[20];
2008         uint16_t mode, inline_data = 0;
2010         p = get_mode(p, &mode);
2011         if (!p)
2012                 die("Corrupt mode: %s", command_buf.buf);
2013         switch (mode) {
2014         case 0644:
2015         case 0755:
2016                 mode |= S_IFREG;
2017         case S_IFREG | 0644:
2018         case S_IFREG | 0755:
2019         case S_IFLNK:
2020         case S_IFGITLINK:
2021                 /* ok */
2022                 break;
2023         default:
2024                 die("Corrupt mode: %s", command_buf.buf);
2025         }
2027         if (*p == ':') {
2028                 char *x;
2029                 oe = find_mark(strtoumax(p + 1, &x, 10));
2030                 hashcpy(sha1, oe->sha1);
2031                 p = x;
2032         } else if (!prefixcmp(p, "inline")) {
2033                 inline_data = 1;
2034                 p += 6;
2035         } else {
2036                 if (get_sha1_hex(p, sha1))
2037                         die("Invalid SHA1: %s", command_buf.buf);
2038                 oe = find_object(sha1);
2039                 p += 40;
2040         }
2041         if (*p++ != ' ')
2042                 die("Missing space after SHA1: %s", command_buf.buf);
2044         strbuf_reset(&uq);
2045         if (!unquote_c_style(&uq, p, &endp)) {
2046                 if (*endp)
2047                         die("Garbage after path in: %s", command_buf.buf);
2048                 p = uq.buf;
2049         }
2051         if (S_ISGITLINK(mode)) {
2052                 if (inline_data)
2053                         die("Git links cannot be specified 'inline': %s",
2054                                 command_buf.buf);
2055                 else if (oe) {
2056                         if (oe->type != OBJ_COMMIT)
2057                                 die("Not a commit (actually a %s): %s",
2058                                         typename(oe->type), command_buf.buf);
2059                 }
2060                 /*
2061                  * Accept the sha1 without checking; it expected to be in
2062                  * another repository.
2063                  */
2064         } else if (inline_data) {
2065                 if (p != uq.buf) {
2066                         strbuf_addstr(&uq, p);
2067                         p = uq.buf;
2068                 }
2069                 read_next_command();
2070                 parse_and_store_blob(&last_blob, sha1, 0);
2071         } else if (oe) {
2072                 if (oe->type != OBJ_BLOB)
2073                         die("Not a blob (actually a %s): %s",
2074                                 typename(oe->type), command_buf.buf);
2075         } else {
2076                 enum object_type type = sha1_object_info(sha1, NULL);
2077                 if (type < 0)
2078                         die("Blob not found: %s", command_buf.buf);
2079                 if (type != OBJ_BLOB)
2080                         die("Not a blob (actually a %s): %s",
2081                             typename(type), command_buf.buf);
2082         }
2084         tree_content_set(&b->branch_tree, p, sha1, mode, NULL);
2087 static void file_change_d(struct branch *b)
2089         const char *p = command_buf.buf + 2;
2090         static struct strbuf uq = STRBUF_INIT;
2091         const char *endp;
2093         strbuf_reset(&uq);
2094         if (!unquote_c_style(&uq, p, &endp)) {
2095                 if (*endp)
2096                         die("Garbage after path in: %s", command_buf.buf);
2097                 p = uq.buf;
2098         }
2099         tree_content_remove(&b->branch_tree, p, NULL);
2102 static void file_change_cr(struct branch *b, int rename)
2104         const char *s, *d;
2105         static struct strbuf s_uq = STRBUF_INIT;
2106         static struct strbuf d_uq = STRBUF_INIT;
2107         const char *endp;
2108         struct tree_entry leaf;
2110         s = command_buf.buf + 2;
2111         strbuf_reset(&s_uq);
2112         if (!unquote_c_style(&s_uq, s, &endp)) {
2113                 if (*endp != ' ')
2114                         die("Missing space after source: %s", command_buf.buf);
2115         } else {
2116                 endp = strchr(s, ' ');
2117                 if (!endp)
2118                         die("Missing space after source: %s", command_buf.buf);
2119                 strbuf_add(&s_uq, s, endp - s);
2120         }
2121         s = s_uq.buf;
2123         endp++;
2124         if (!*endp)
2125                 die("Missing dest: %s", command_buf.buf);
2127         d = endp;
2128         strbuf_reset(&d_uq);
2129         if (!unquote_c_style(&d_uq, d, &endp)) {
2130                 if (*endp)
2131                         die("Garbage after dest in: %s", command_buf.buf);
2132                 d = d_uq.buf;
2133         }
2135         memset(&leaf, 0, sizeof(leaf));
2136         if (rename)
2137                 tree_content_remove(&b->branch_tree, s, &leaf);
2138         else
2139                 tree_content_get(&b->branch_tree, s, &leaf);
2140         if (!leaf.versions[1].mode)
2141                 die("Path %s not in branch", s);
2142         tree_content_set(&b->branch_tree, d,
2143                 leaf.versions[1].sha1,
2144                 leaf.versions[1].mode,
2145                 leaf.tree);
2148 static void note_change_n(struct branch *b)
2150         const char *p = command_buf.buf + 2;
2151         static struct strbuf uq = STRBUF_INIT;
2152         struct object_entry *oe = oe;
2153         struct branch *s;
2154         unsigned char sha1[20], commit_sha1[20];
2155         uint16_t inline_data = 0;
2157         /* <dataref> or 'inline' */
2158         if (*p == ':') {
2159                 char *x;
2160                 oe = find_mark(strtoumax(p + 1, &x, 10));
2161                 hashcpy(sha1, oe->sha1);
2162                 p = x;
2163         } else if (!prefixcmp(p, "inline")) {
2164                 inline_data = 1;
2165                 p += 6;
2166         } else {
2167                 if (get_sha1_hex(p, sha1))
2168                         die("Invalid SHA1: %s", command_buf.buf);
2169                 oe = find_object(sha1);
2170                 p += 40;
2171         }
2172         if (*p++ != ' ')
2173                 die("Missing space after SHA1: %s", command_buf.buf);
2175         /* <committish> */
2176         s = lookup_branch(p);
2177         if (s) {
2178                 hashcpy(commit_sha1, s->sha1);
2179         } else if (*p == ':') {
2180                 uintmax_t commit_mark = strtoumax(p + 1, NULL, 10);
2181                 struct object_entry *commit_oe = find_mark(commit_mark);
2182                 if (commit_oe->type != OBJ_COMMIT)
2183                         die("Mark :%" PRIuMAX " not a commit", commit_mark);
2184                 hashcpy(commit_sha1, commit_oe->sha1);
2185         } else if (!get_sha1(p, commit_sha1)) {
2186                 unsigned long size;
2187                 char *buf = read_object_with_reference(commit_sha1,
2188                         commit_type, &size, commit_sha1);
2189                 if (!buf || size < 46)
2190                         die("Not a valid commit: %s", p);
2191                 free(buf);
2192         } else
2193                 die("Invalid ref name or SHA1 expression: %s", p);
2195         if (inline_data) {
2196                 if (p != uq.buf) {
2197                         strbuf_addstr(&uq, p);
2198                         p = uq.buf;
2199                 }
2200                 read_next_command();
2201                 parse_and_store_blob(&last_blob, sha1, 0);
2202         } else if (oe) {
2203                 if (oe->type != OBJ_BLOB)
2204                         die("Not a blob (actually a %s): %s",
2205                                 typename(oe->type), command_buf.buf);
2206         } else {
2207                 enum object_type type = sha1_object_info(sha1, NULL);
2208                 if (type < 0)
2209                         die("Blob not found: %s", command_buf.buf);
2210                 if (type != OBJ_BLOB)
2211                         die("Not a blob (actually a %s): %s",
2212                             typename(type), command_buf.buf);
2213         }
2215         tree_content_set(&b->branch_tree, sha1_to_hex(commit_sha1), sha1,
2216                 S_IFREG | 0644, NULL);
2219 static void file_change_deleteall(struct branch *b)
2221         release_tree_content_recursive(b->branch_tree.tree);
2222         hashclr(b->branch_tree.versions[0].sha1);
2223         hashclr(b->branch_tree.versions[1].sha1);
2224         load_tree(&b->branch_tree);
2227 static void parse_from_commit(struct branch *b, char *buf, unsigned long size)
2229         if (!buf || size < 46)
2230                 die("Not a valid commit: %s", sha1_to_hex(b->sha1));
2231         if (memcmp("tree ", buf, 5)
2232                 || get_sha1_hex(buf + 5, b->branch_tree.versions[1].sha1))
2233                 die("The commit %s is corrupt", sha1_to_hex(b->sha1));
2234         hashcpy(b->branch_tree.versions[0].sha1,
2235                 b->branch_tree.versions[1].sha1);
2238 static void parse_from_existing(struct branch *b)
2240         if (is_null_sha1(b->sha1)) {
2241                 hashclr(b->branch_tree.versions[0].sha1);
2242                 hashclr(b->branch_tree.versions[1].sha1);
2243         } else {
2244                 unsigned long size;
2245                 char *buf;
2247                 buf = read_object_with_reference(b->sha1,
2248                         commit_type, &size, b->sha1);
2249                 parse_from_commit(b, buf, size);
2250                 free(buf);
2251         }
2254 static int parse_from(struct branch *b)
2256         const char *from;
2257         struct branch *s;
2259         if (prefixcmp(command_buf.buf, "from "))
2260                 return 0;
2262         if (b->branch_tree.tree) {
2263                 release_tree_content_recursive(b->branch_tree.tree);
2264                 b->branch_tree.tree = NULL;
2265         }
2267         from = strchr(command_buf.buf, ' ') + 1;
2268         s = lookup_branch(from);
2269         if (b == s)
2270                 die("Can't create a branch from itself: %s", b->name);
2271         else if (s) {
2272                 unsigned char *t = s->branch_tree.versions[1].sha1;
2273                 hashcpy(b->sha1, s->sha1);
2274                 hashcpy(b->branch_tree.versions[0].sha1, t);
2275                 hashcpy(b->branch_tree.versions[1].sha1, t);
2276         } else if (*from == ':') {
2277                 uintmax_t idnum = strtoumax(from + 1, NULL, 10);
2278                 struct object_entry *oe = find_mark(idnum);
2279                 if (oe->type != OBJ_COMMIT)
2280                         die("Mark :%" PRIuMAX " not a commit", idnum);
2281                 hashcpy(b->sha1, oe->sha1);
2282                 if (oe->pack_id != MAX_PACK_ID) {
2283                         unsigned long size;
2284                         char *buf = gfi_unpack_entry(oe, &size);
2285                         parse_from_commit(b, buf, size);
2286                         free(buf);
2287                 } else
2288                         parse_from_existing(b);
2289         } else if (!get_sha1(from, b->sha1))
2290                 parse_from_existing(b);
2291         else
2292                 die("Invalid ref name or SHA1 expression: %s", from);
2294         read_next_command();
2295         return 1;
2298 static struct hash_list *parse_merge(unsigned int *count)
2300         struct hash_list *list = NULL, *n, *e = e;
2301         const char *from;
2302         struct branch *s;
2304         *count = 0;
2305         while (!prefixcmp(command_buf.buf, "merge ")) {
2306                 from = strchr(command_buf.buf, ' ') + 1;
2307                 n = xmalloc(sizeof(*n));
2308                 s = lookup_branch(from);
2309                 if (s)
2310                         hashcpy(n->sha1, s->sha1);
2311                 else if (*from == ':') {
2312                         uintmax_t idnum = strtoumax(from + 1, NULL, 10);
2313                         struct object_entry *oe = find_mark(idnum);
2314                         if (oe->type != OBJ_COMMIT)
2315                                 die("Mark :%" PRIuMAX " not a commit", idnum);
2316                         hashcpy(n->sha1, oe->sha1);
2317                 } else if (!get_sha1(from, n->sha1)) {
2318                         unsigned long size;
2319                         char *buf = read_object_with_reference(n->sha1,
2320                                 commit_type, &size, n->sha1);
2321                         if (!buf || size < 46)
2322                                 die("Not a valid commit: %s", from);
2323                         free(buf);
2324                 } else
2325                         die("Invalid ref name or SHA1 expression: %s", from);
2327                 n->next = NULL;
2328                 if (list)
2329                         e->next = n;
2330                 else
2331                         list = n;
2332                 e = n;
2333                 (*count)++;
2334                 read_next_command();
2335         }
2336         return list;
2339 static void parse_new_commit(void)
2341         static struct strbuf msg = STRBUF_INIT;
2342         struct branch *b;
2343         char *sp;
2344         char *author = NULL;
2345         char *committer = NULL;
2346         struct hash_list *merge_list = NULL;
2347         unsigned int merge_count;
2349         /* Obtain the branch name from the rest of our command */
2350         sp = strchr(command_buf.buf, ' ') + 1;
2351         b = lookup_branch(sp);
2352         if (!b)
2353                 b = new_branch(sp);
2355         read_next_command();
2356         parse_mark();
2357         if (!prefixcmp(command_buf.buf, "author ")) {
2358                 author = parse_ident(command_buf.buf + 7);
2359                 read_next_command();
2360         }
2361         if (!prefixcmp(command_buf.buf, "committer ")) {
2362                 committer = parse_ident(command_buf.buf + 10);
2363                 read_next_command();
2364         }
2365         if (!committer)
2366                 die("Expected committer but didn't get one");
2367         parse_data(&msg, 0, NULL);
2368         read_next_command();
2369         parse_from(b);
2370         merge_list = parse_merge(&merge_count);
2372         /* ensure the branch is active/loaded */
2373         if (!b->branch_tree.tree || !max_active_branches) {
2374                 unload_one_branch();
2375                 load_branch(b);
2376         }
2378         /* file_change* */
2379         while (command_buf.len > 0) {
2380                 if (!prefixcmp(command_buf.buf, "M "))
2381                         file_change_m(b);
2382                 else if (!prefixcmp(command_buf.buf, "D "))
2383                         file_change_d(b);
2384                 else if (!prefixcmp(command_buf.buf, "R "))
2385                         file_change_cr(b, 1);
2386                 else if (!prefixcmp(command_buf.buf, "C "))
2387                         file_change_cr(b, 0);
2388                 else if (!prefixcmp(command_buf.buf, "N "))
2389                         note_change_n(b);
2390                 else if (!strcmp("deleteall", command_buf.buf))
2391                         file_change_deleteall(b);
2392                 else {
2393                         unread_command_buf = 1;
2394                         break;
2395                 }
2396                 if (read_next_command() == EOF)
2397                         break;
2398         }
2400         /* build the tree and the commit */
2401         store_tree(&b->branch_tree);
2402         hashcpy(b->branch_tree.versions[0].sha1,
2403                 b->branch_tree.versions[1].sha1);
2405         strbuf_reset(&new_data);
2406         strbuf_addf(&new_data, "tree %s\n",
2407                 sha1_to_hex(b->branch_tree.versions[1].sha1));
2408         if (!is_null_sha1(b->sha1))
2409                 strbuf_addf(&new_data, "parent %s\n", sha1_to_hex(b->sha1));
2410         while (merge_list) {
2411                 struct hash_list *next = merge_list->next;
2412                 strbuf_addf(&new_data, "parent %s\n", sha1_to_hex(merge_list->sha1));
2413                 free(merge_list);
2414                 merge_list = next;
2415         }
2416         strbuf_addf(&new_data,
2417                 "author %s\n"
2418                 "committer %s\n"
2419                 "\n",
2420                 author ? author : committer, committer);
2421         strbuf_addbuf(&new_data, &msg);
2422         free(author);
2423         free(committer);
2425         if (!store_object(OBJ_COMMIT, &new_data, NULL, b->sha1, next_mark))
2426                 b->pack_id = pack_id;
2427         b->last_commit = object_count_by_type[OBJ_COMMIT];
2430 static void parse_new_tag(void)
2432         static struct strbuf msg = STRBUF_INIT;
2433         char *sp;
2434         const char *from;
2435         char *tagger;
2436         struct branch *s;
2437         struct tag *t;
2438         uintmax_t from_mark = 0;
2439         unsigned char sha1[20];
2440         enum object_type type;
2442         /* Obtain the new tag name from the rest of our command */
2443         sp = strchr(command_buf.buf, ' ') + 1;
2444         t = pool_alloc(sizeof(struct tag));
2445         t->next_tag = NULL;
2446         t->name = pool_strdup(sp);
2447         if (last_tag)
2448                 last_tag->next_tag = t;
2449         else
2450                 first_tag = t;
2451         last_tag = t;
2452         read_next_command();
2454         /* from ... */
2455         if (prefixcmp(command_buf.buf, "from "))
2456                 die("Expected from command, got %s", command_buf.buf);
2457         from = strchr(command_buf.buf, ' ') + 1;
2458         s = lookup_branch(from);
2459         if (s) {
2460                 hashcpy(sha1, s->sha1);
2461                 type = OBJ_COMMIT;
2462         } else if (*from == ':') {
2463                 struct object_entry *oe;
2464                 from_mark = strtoumax(from + 1, NULL, 10);
2465                 oe = find_mark(from_mark);
2466                 type = oe->type;
2467                 hashcpy(sha1, oe->sha1);
2468         } else if (!get_sha1(from, sha1)) {
2469                 unsigned long size;
2470                 char *buf;
2472                 buf = read_sha1_file(sha1, &type, &size);
2473                 if (!buf || size < 46)
2474                         die("Not a valid commit: %s", from);
2475                 free(buf);
2476         } else
2477                 die("Invalid ref name or SHA1 expression: %s", from);
2478         read_next_command();
2480         /* tagger ... */
2481         if (!prefixcmp(command_buf.buf, "tagger ")) {
2482                 tagger = parse_ident(command_buf.buf + 7);
2483                 read_next_command();
2484         } else
2485                 tagger = NULL;
2487         /* tag payload/message */
2488         parse_data(&msg, 0, NULL);
2490         /* build the tag object */
2491         strbuf_reset(&new_data);
2493         strbuf_addf(&new_data,
2494                     "object %s\n"
2495                     "type %s\n"
2496                     "tag %s\n",
2497                     sha1_to_hex(sha1), typename(type), t->name);
2498         if (tagger)
2499                 strbuf_addf(&new_data,
2500                             "tagger %s\n", tagger);
2501         strbuf_addch(&new_data, '\n');
2502         strbuf_addbuf(&new_data, &msg);
2503         free(tagger);
2505         if (store_object(OBJ_TAG, &new_data, NULL, t->sha1, 0))
2506                 t->pack_id = MAX_PACK_ID;
2507         else
2508                 t->pack_id = pack_id;
2511 static void parse_reset_branch(void)
2513         struct branch *b;
2514         char *sp;
2516         /* Obtain the branch name from the rest of our command */
2517         sp = strchr(command_buf.buf, ' ') + 1;
2518         b = lookup_branch(sp);
2519         if (b) {
2520                 hashclr(b->sha1);
2521                 hashclr(b->branch_tree.versions[0].sha1);
2522                 hashclr(b->branch_tree.versions[1].sha1);
2523                 if (b->branch_tree.tree) {
2524                         release_tree_content_recursive(b->branch_tree.tree);
2525                         b->branch_tree.tree = NULL;
2526                 }
2527         }
2528         else
2529                 b = new_branch(sp);
2530         read_next_command();
2531         parse_from(b);
2532         if (command_buf.len > 0)
2533                 unread_command_buf = 1;
2536 static void parse_checkpoint(void)
2538         if (object_count) {
2539                 cycle_packfile();
2540                 dump_branches();
2541                 dump_tags();
2542                 dump_marks();
2543         }
2544         skip_optional_lf();
2547 static void parse_progress(void)
2549         fwrite(command_buf.buf, 1, command_buf.len, stdout);
2550         fputc('\n', stdout);
2551         fflush(stdout);
2552         skip_optional_lf();
2555 static void import_marks(const char *input_file)
2557         char line[512];
2558         FILE *f = fopen(input_file, "r");
2559         if (!f)
2560                 die_errno("cannot read '%s'", input_file);
2561         while (fgets(line, sizeof(line), f)) {
2562                 uintmax_t mark;
2563                 char *end;
2564                 unsigned char sha1[20];
2565                 struct object_entry *e;
2567                 end = strchr(line, '\n');
2568                 if (line[0] != ':' || !end)
2569                         die("corrupt mark line: %s", line);
2570                 *end = 0;
2571                 mark = strtoumax(line + 1, &end, 10);
2572                 if (!mark || end == line + 1
2573                         || *end != ' ' || get_sha1(end + 1, sha1))
2574                         die("corrupt mark line: %s", line);
2575                 e = find_object(sha1);
2576                 if (!e) {
2577                         enum object_type type = sha1_object_info(sha1, NULL);
2578                         if (type < 0)
2579                                 die("object not found: %s", sha1_to_hex(sha1));
2580                         e = insert_object(sha1);
2581                         e->type = type;
2582                         e->pack_id = MAX_PACK_ID;
2583                         e->offset = 1; /* just not zero! */
2584                 }
2585                 insert_mark(mark, e);
2586         }
2587         fclose(f);
2590 static int git_pack_config(const char *k, const char *v, void *cb)
2592         if (!strcmp(k, "pack.depth")) {
2593                 max_depth = git_config_int(k, v);
2594                 if (max_depth > MAX_DEPTH)
2595                         max_depth = MAX_DEPTH;
2596                 return 0;
2597         }
2598         if (!strcmp(k, "pack.compression")) {
2599                 int level = git_config_int(k, v);
2600                 if (level == -1)
2601                         level = Z_DEFAULT_COMPRESSION;
2602                 else if (level < 0 || level > Z_BEST_COMPRESSION)
2603                         die("bad pack compression level %d", level);
2604                 pack_compression_level = level;
2605                 pack_compression_seen = 1;
2606                 return 0;
2607         }
2608         if (!strcmp(k, "core.bigfilethreshold")) {
2609                 long n = git_config_int(k, v);
2610                 big_file_threshold = 0 < n ? n : 0;
2611         }
2612         return git_default_config(k, v, cb);
2615 static const char fast_import_usage[] =
2616 "git fast-import [--date-format=f] [--max-pack-size=n] [--big-file-threshold=n] [--depth=n] [--active-branches=n] [--export-marks=marks.file]";
2618 int main(int argc, const char **argv)
2620         unsigned int i, show_stats = 1;
2622         git_extract_argv0_path(argv[0]);
2624         if (argc == 2 && !strcmp(argv[1], "-h"))
2625                 usage(fast_import_usage);
2627         setup_git_directory();
2628         git_config(git_pack_config, NULL);
2629         if (!pack_compression_seen && core_compression_seen)
2630                 pack_compression_level = core_compression_level;
2632         alloc_objects(object_entry_alloc);
2633         strbuf_init(&command_buf, 0);
2634         atom_table = xcalloc(atom_table_sz, sizeof(struct atom_str*));
2635         branch_table = xcalloc(branch_table_sz, sizeof(struct branch*));
2636         avail_tree_table = xcalloc(avail_tree_table_sz, sizeof(struct avail_tree_content*));
2637         marks = pool_calloc(1, sizeof(struct mark_set));
2639         for (i = 1; i < argc; i++) {
2640                 const char *a = argv[i];
2642                 if (*a != '-' || !strcmp(a, "--"))
2643                         break;
2644                 else if (!prefixcmp(a, "--date-format=")) {
2645                         const char *fmt = a + 14;
2646                         if (!strcmp(fmt, "raw"))
2647                                 whenspec = WHENSPEC_RAW;
2648                         else if (!strcmp(fmt, "rfc2822"))
2649                                 whenspec = WHENSPEC_RFC2822;
2650                         else if (!strcmp(fmt, "now"))
2651                                 whenspec = WHENSPEC_NOW;
2652                         else
2653                                 die("unknown --date-format argument %s", fmt);
2654                 }
2655                 else if (!prefixcmp(a, "--max-pack-size="))
2656                         max_packsize = strtoumax(a + 16, NULL, 0) * 1024 * 1024;
2657                 else if (!prefixcmp(a, "--big-file-threshold=")) {
2658                         unsigned long v;
2659                         if (!git_parse_ulong(a + 21, &v))
2660                                 usage(fast_import_usage);
2661                         big_file_threshold = v;
2662                 } else if (!prefixcmp(a, "--depth=")) {
2663                         max_depth = strtoul(a + 8, NULL, 0);
2664                         if (max_depth > MAX_DEPTH)
2665                                 die("--depth cannot exceed %u", MAX_DEPTH);
2666                 }
2667                 else if (!prefixcmp(a, "--active-branches="))
2668                         max_active_branches = strtoul(a + 18, NULL, 0);
2669                 else if (!prefixcmp(a, "--import-marks="))
2670                         import_marks(a + 15);
2671                 else if (!prefixcmp(a, "--export-marks="))
2672                         mark_file = a + 15;
2673                 else if (!prefixcmp(a, "--export-pack-edges=")) {
2674                         if (pack_edges)
2675                                 fclose(pack_edges);
2676                         pack_edges = fopen(a + 20, "a");
2677                         if (!pack_edges)
2678                                 die_errno("Cannot open '%s'", a + 20);
2679                 } else if (!strcmp(a, "--force"))
2680                         force_update = 1;
2681                 else if (!strcmp(a, "--quiet"))
2682                         show_stats = 0;
2683                 else if (!strcmp(a, "--stats"))
2684                         show_stats = 1;
2685                 else
2686                         die("unknown option %s", a);
2687         }
2688         if (i != argc)
2689                 usage(fast_import_usage);
2691         rc_free = pool_alloc(cmd_save * sizeof(*rc_free));
2692         for (i = 0; i < (cmd_save - 1); i++)
2693                 rc_free[i].next = &rc_free[i + 1];
2694         rc_free[cmd_save - 1].next = NULL;
2696         prepare_packed_git();
2697         start_packfile();
2698         set_die_routine(die_nicely);
2699         while (read_next_command() != EOF) {
2700                 if (!strcmp("blob", command_buf.buf))
2701                         parse_new_blob();
2702                 else if (!prefixcmp(command_buf.buf, "commit "))
2703                         parse_new_commit();
2704                 else if (!prefixcmp(command_buf.buf, "tag "))
2705                         parse_new_tag();
2706                 else if (!prefixcmp(command_buf.buf, "reset "))
2707                         parse_reset_branch();
2708                 else if (!strcmp("checkpoint", command_buf.buf))
2709                         parse_checkpoint();
2710                 else if (!prefixcmp(command_buf.buf, "progress "))
2711                         parse_progress();
2712                 else
2713                         die("Unsupported command: %s", command_buf.buf);
2714         }
2715         end_packfile();
2717         dump_branches();
2718         dump_tags();
2719         unkeep_all_packs();
2720         dump_marks();
2722         if (pack_edges)
2723                 fclose(pack_edges);
2725         if (show_stats) {
2726                 uintmax_t total_count = 0, duplicate_count = 0;
2727                 for (i = 0; i < ARRAY_SIZE(object_count_by_type); i++)
2728                         total_count += object_count_by_type[i];
2729                 for (i = 0; i < ARRAY_SIZE(duplicate_count_by_type); i++)
2730                         duplicate_count += duplicate_count_by_type[i];
2732                 fprintf(stderr, "%s statistics:\n", argv[0]);
2733                 fprintf(stderr, "---------------------------------------------------------------------\n");
2734                 fprintf(stderr, "Alloc'd objects: %10" PRIuMAX "\n", alloc_count);
2735                 fprintf(stderr, "Total objects:   %10" PRIuMAX " (%10" PRIuMAX " duplicates                  )\n", total_count, duplicate_count);
2736                 fprintf(stderr, "      blobs  :   %10" PRIuMAX " (%10" PRIuMAX " duplicates %10" PRIuMAX " deltas)\n", object_count_by_type[OBJ_BLOB], duplicate_count_by_type[OBJ_BLOB], delta_count_by_type[OBJ_BLOB]);
2737                 fprintf(stderr, "      trees  :   %10" PRIuMAX " (%10" PRIuMAX " duplicates %10" PRIuMAX " deltas)\n", object_count_by_type[OBJ_TREE], duplicate_count_by_type[OBJ_TREE], delta_count_by_type[OBJ_TREE]);
2738                 fprintf(stderr, "      commits:   %10" PRIuMAX " (%10" PRIuMAX " duplicates %10" PRIuMAX " deltas)\n", object_count_by_type[OBJ_COMMIT], duplicate_count_by_type[OBJ_COMMIT], delta_count_by_type[OBJ_COMMIT]);
2739                 fprintf(stderr, "      tags   :   %10" PRIuMAX " (%10" PRIuMAX " duplicates %10" PRIuMAX " deltas)\n", object_count_by_type[OBJ_TAG], duplicate_count_by_type[OBJ_TAG], delta_count_by_type[OBJ_TAG]);
2740                 fprintf(stderr, "Total branches:  %10lu (%10lu loads     )\n", branch_count, branch_load_count);
2741                 fprintf(stderr, "      marks:     %10" PRIuMAX " (%10" PRIuMAX " unique    )\n", (((uintmax_t)1) << marks->shift) * 1024, marks_set_count);
2742                 fprintf(stderr, "      atoms:     %10u\n", atom_cnt);
2743                 fprintf(stderr, "Memory total:    %10" PRIuMAX " KiB\n", (total_allocd + alloc_count*sizeof(struct object_entry))/1024);
2744                 fprintf(stderr, "       pools:    %10lu KiB\n", (unsigned long)(total_allocd/1024));
2745                 fprintf(stderr, "     objects:    %10" PRIuMAX " KiB\n", (alloc_count*sizeof(struct object_entry))/1024);
2746                 fprintf(stderr, "---------------------------------------------------------------------\n");
2747                 pack_report();
2748                 fprintf(stderr, "---------------------------------------------------------------------\n");
2749                 fprintf(stderr, "\n");
2750         }
2752         return failure ? 1 : 0;