Code

fast-import: add option command
[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 int force_update;
284 static int pack_compression_level = Z_DEFAULT_COMPRESSION;
285 static int pack_compression_seen;
287 /* Stats and misc. counters */
288 static uintmax_t alloc_count;
289 static uintmax_t marks_set_count;
290 static uintmax_t object_count_by_type[1 << TYPE_BITS];
291 static uintmax_t duplicate_count_by_type[1 << TYPE_BITS];
292 static uintmax_t delta_count_by_type[1 << TYPE_BITS];
293 static unsigned long object_count;
294 static unsigned long branch_count;
295 static unsigned long branch_load_count;
296 static int failure;
297 static FILE *pack_edges;
298 static unsigned int show_stats = 1;
299 static int global_argc;
300 static const char **global_argv;
302 /* Memory pools */
303 static size_t mem_pool_alloc = 2*1024*1024 - sizeof(struct mem_pool);
304 static size_t total_allocd;
305 static struct mem_pool *mem_pool;
307 /* Atom management */
308 static unsigned int atom_table_sz = 4451;
309 static unsigned int atom_cnt;
310 static struct atom_str **atom_table;
312 /* The .pack file being generated */
313 static unsigned int pack_id;
314 static struct packed_git *pack_data;
315 static struct packed_git **all_packs;
316 static unsigned long pack_size;
318 /* Table of objects we've written. */
319 static unsigned int object_entry_alloc = 5000;
320 static struct object_entry_pool *blocks;
321 static struct object_entry *object_table[1 << 16];
322 static struct mark_set *marks;
323 static const char *export_marks_file;
324 static const char *import_marks_file;
326 /* Our last blob */
327 static struct last_object last_blob = { STRBUF_INIT, 0, 0, 0 };
329 /* Tree management */
330 static unsigned int tree_entry_alloc = 1000;
331 static void *avail_tree_entry;
332 static unsigned int avail_tree_table_sz = 100;
333 static struct avail_tree_content **avail_tree_table;
334 static struct strbuf old_tree = STRBUF_INIT;
335 static struct strbuf new_tree = STRBUF_INIT;
337 /* Branch data */
338 static unsigned long max_active_branches = 5;
339 static unsigned long cur_active_branches;
340 static unsigned long branch_table_sz = 1039;
341 static struct branch **branch_table;
342 static struct branch *active_branches;
344 /* Tag data */
345 static struct tag *first_tag;
346 static struct tag *last_tag;
348 /* Input stream parsing */
349 static whenspec_type whenspec = WHENSPEC_RAW;
350 static struct strbuf command_buf = STRBUF_INIT;
351 static int unread_command_buf;
352 static struct recent_command cmd_hist = {&cmd_hist, &cmd_hist, NULL};
353 static struct recent_command *cmd_tail = &cmd_hist;
354 static struct recent_command *rc_free;
355 static unsigned int cmd_save = 100;
356 static uintmax_t next_mark;
357 static struct strbuf new_data = STRBUF_INIT;
358 static int seen_data_command;
360 static void parse_argv(void);
362 static void write_branch_report(FILE *rpt, struct branch *b)
364         fprintf(rpt, "%s:\n", b->name);
366         fprintf(rpt, "  status      :");
367         if (b->active)
368                 fputs(" active", rpt);
369         if (b->branch_tree.tree)
370                 fputs(" loaded", rpt);
371         if (is_null_sha1(b->branch_tree.versions[1].sha1))
372                 fputs(" dirty", rpt);
373         fputc('\n', rpt);
375         fprintf(rpt, "  tip commit  : %s\n", sha1_to_hex(b->sha1));
376         fprintf(rpt, "  old tree    : %s\n", sha1_to_hex(b->branch_tree.versions[0].sha1));
377         fprintf(rpt, "  cur tree    : %s\n", sha1_to_hex(b->branch_tree.versions[1].sha1));
378         fprintf(rpt, "  commit clock: %" PRIuMAX "\n", b->last_commit);
380         fputs("  last pack   : ", rpt);
381         if (b->pack_id < MAX_PACK_ID)
382                 fprintf(rpt, "%u", b->pack_id);
383         fputc('\n', rpt);
385         fputc('\n', rpt);
388 static void dump_marks_helper(FILE *, uintmax_t, struct mark_set *);
390 static void write_crash_report(const char *err)
392         char *loc = git_path("fast_import_crash_%"PRIuMAX, (uintmax_t) getpid());
393         FILE *rpt = fopen(loc, "w");
394         struct branch *b;
395         unsigned long lu;
396         struct recent_command *rc;
398         if (!rpt) {
399                 error("can't write crash report %s: %s", loc, strerror(errno));
400                 return;
401         }
403         fprintf(stderr, "fast-import: dumping crash report to %s\n", loc);
405         fprintf(rpt, "fast-import crash report:\n");
406         fprintf(rpt, "    fast-import process: %"PRIuMAX"\n", (uintmax_t) getpid());
407         fprintf(rpt, "    parent process     : %"PRIuMAX"\n", (uintmax_t) getppid());
408         fprintf(rpt, "    at %s\n", show_date(time(NULL), 0, DATE_LOCAL));
409         fputc('\n', rpt);
411         fputs("fatal: ", rpt);
412         fputs(err, rpt);
413         fputc('\n', rpt);
415         fputc('\n', rpt);
416         fputs("Most Recent Commands Before Crash\n", rpt);
417         fputs("---------------------------------\n", rpt);
418         for (rc = cmd_hist.next; rc != &cmd_hist; rc = rc->next) {
419                 if (rc->next == &cmd_hist)
420                         fputs("* ", rpt);
421                 else
422                         fputs("  ", rpt);
423                 fputs(rc->buf, rpt);
424                 fputc('\n', rpt);
425         }
427         fputc('\n', rpt);
428         fputs("Active Branch LRU\n", rpt);
429         fputs("-----------------\n", rpt);
430         fprintf(rpt, "    active_branches = %lu cur, %lu max\n",
431                 cur_active_branches,
432                 max_active_branches);
433         fputc('\n', rpt);
434         fputs("  pos  clock name\n", rpt);
435         fputs("  ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n", rpt);
436         for (b = active_branches, lu = 0; b; b = b->active_next_branch)
437                 fprintf(rpt, "  %2lu) %6" PRIuMAX" %s\n",
438                         ++lu, b->last_commit, b->name);
440         fputc('\n', rpt);
441         fputs("Inactive Branches\n", rpt);
442         fputs("-----------------\n", rpt);
443         for (lu = 0; lu < branch_table_sz; lu++) {
444                 for (b = branch_table[lu]; b; b = b->table_next_branch)
445                         write_branch_report(rpt, b);
446         }
448         if (first_tag) {
449                 struct tag *tg;
450                 fputc('\n', rpt);
451                 fputs("Annotated Tags\n", rpt);
452                 fputs("--------------\n", rpt);
453                 for (tg = first_tag; tg; tg = tg->next_tag) {
454                         fputs(sha1_to_hex(tg->sha1), rpt);
455                         fputc(' ', rpt);
456                         fputs(tg->name, rpt);
457                         fputc('\n', rpt);
458                 }
459         }
461         fputc('\n', rpt);
462         fputs("Marks\n", rpt);
463         fputs("-----\n", rpt);
464         if (export_marks_file)
465                 fprintf(rpt, "  exported to %s\n", export_marks_file);
466         else
467                 dump_marks_helper(rpt, 0, marks);
469         fputc('\n', rpt);
470         fputs("-------------------\n", rpt);
471         fputs("END OF CRASH REPORT\n", rpt);
472         fclose(rpt);
475 static void end_packfile(void);
476 static void unkeep_all_packs(void);
477 static void dump_marks(void);
479 static NORETURN void die_nicely(const char *err, va_list params)
481         static int zombie;
482         char message[2 * PATH_MAX];
484         vsnprintf(message, sizeof(message), err, params);
485         fputs("fatal: ", stderr);
486         fputs(message, stderr);
487         fputc('\n', stderr);
489         if (!zombie) {
490                 zombie = 1;
491                 write_crash_report(message);
492                 end_packfile();
493                 unkeep_all_packs();
494                 dump_marks();
495         }
496         exit(128);
499 static void alloc_objects(unsigned int cnt)
501         struct object_entry_pool *b;
503         b = xmalloc(sizeof(struct object_entry_pool)
504                 + cnt * sizeof(struct object_entry));
505         b->next_pool = blocks;
506         b->next_free = b->entries;
507         b->end = b->entries + cnt;
508         blocks = b;
509         alloc_count += cnt;
512 static struct object_entry *new_object(unsigned char *sha1)
514         struct object_entry *e;
516         if (blocks->next_free == blocks->end)
517                 alloc_objects(object_entry_alloc);
519         e = blocks->next_free++;
520         hashcpy(e->sha1, sha1);
521         return e;
524 static struct object_entry *find_object(unsigned char *sha1)
526         unsigned int h = sha1[0] << 8 | sha1[1];
527         struct object_entry *e;
528         for (e = object_table[h]; e; e = e->next)
529                 if (!hashcmp(sha1, e->sha1))
530                         return e;
531         return NULL;
534 static struct object_entry *insert_object(unsigned char *sha1)
536         unsigned int h = sha1[0] << 8 | sha1[1];
537         struct object_entry *e = object_table[h];
538         struct object_entry *p = NULL;
540         while (e) {
541                 if (!hashcmp(sha1, e->sha1))
542                         return e;
543                 p = e;
544                 e = e->next;
545         }
547         e = new_object(sha1);
548         e->next = NULL;
549         e->offset = 0;
550         if (p)
551                 p->next = e;
552         else
553                 object_table[h] = e;
554         return e;
557 static unsigned int hc_str(const char *s, size_t len)
559         unsigned int r = 0;
560         while (len-- > 0)
561                 r = r * 31 + *s++;
562         return r;
565 static void *pool_alloc(size_t len)
567         struct mem_pool *p;
568         void *r;
570         /* round up to a 'uintmax_t' alignment */
571         if (len & (sizeof(uintmax_t) - 1))
572                 len += sizeof(uintmax_t) - (len & (sizeof(uintmax_t) - 1));
574         for (p = mem_pool; p; p = p->next_pool)
575                 if ((p->end - p->next_free >= len))
576                         break;
578         if (!p) {
579                 if (len >= (mem_pool_alloc/2)) {
580                         total_allocd += len;
581                         return xmalloc(len);
582                 }
583                 total_allocd += sizeof(struct mem_pool) + mem_pool_alloc;
584                 p = xmalloc(sizeof(struct mem_pool) + mem_pool_alloc);
585                 p->next_pool = mem_pool;
586                 p->next_free = (char *) p->space;
587                 p->end = p->next_free + mem_pool_alloc;
588                 mem_pool = p;
589         }
591         r = p->next_free;
592         p->next_free += len;
593         return r;
596 static void *pool_calloc(size_t count, size_t size)
598         size_t len = count * size;
599         void *r = pool_alloc(len);
600         memset(r, 0, len);
601         return r;
604 static char *pool_strdup(const char *s)
606         char *r = pool_alloc(strlen(s) + 1);
607         strcpy(r, s);
608         return r;
611 static void insert_mark(uintmax_t idnum, struct object_entry *oe)
613         struct mark_set *s = marks;
614         while ((idnum >> s->shift) >= 1024) {
615                 s = pool_calloc(1, sizeof(struct mark_set));
616                 s->shift = marks->shift + 10;
617                 s->data.sets[0] = marks;
618                 marks = s;
619         }
620         while (s->shift) {
621                 uintmax_t i = idnum >> s->shift;
622                 idnum -= i << s->shift;
623                 if (!s->data.sets[i]) {
624                         s->data.sets[i] = pool_calloc(1, sizeof(struct mark_set));
625                         s->data.sets[i]->shift = s->shift - 10;
626                 }
627                 s = s->data.sets[i];
628         }
629         if (!s->data.marked[idnum])
630                 marks_set_count++;
631         s->data.marked[idnum] = oe;
634 static struct object_entry *find_mark(uintmax_t idnum)
636         uintmax_t orig_idnum = idnum;
637         struct mark_set *s = marks;
638         struct object_entry *oe = NULL;
639         if ((idnum >> s->shift) < 1024) {
640                 while (s && s->shift) {
641                         uintmax_t i = idnum >> s->shift;
642                         idnum -= i << s->shift;
643                         s = s->data.sets[i];
644                 }
645                 if (s)
646                         oe = s->data.marked[idnum];
647         }
648         if (!oe)
649                 die("mark :%" PRIuMAX " not declared", orig_idnum);
650         return oe;
653 static struct atom_str *to_atom(const char *s, unsigned short len)
655         unsigned int hc = hc_str(s, len) % atom_table_sz;
656         struct atom_str *c;
658         for (c = atom_table[hc]; c; c = c->next_atom)
659                 if (c->str_len == len && !strncmp(s, c->str_dat, len))
660                         return c;
662         c = pool_alloc(sizeof(struct atom_str) + len + 1);
663         c->str_len = len;
664         strncpy(c->str_dat, s, len);
665         c->str_dat[len] = 0;
666         c->next_atom = atom_table[hc];
667         atom_table[hc] = c;
668         atom_cnt++;
669         return c;
672 static struct branch *lookup_branch(const char *name)
674         unsigned int hc = hc_str(name, strlen(name)) % branch_table_sz;
675         struct branch *b;
677         for (b = branch_table[hc]; b; b = b->table_next_branch)
678                 if (!strcmp(name, b->name))
679                         return b;
680         return NULL;
683 static struct branch *new_branch(const char *name)
685         unsigned int hc = hc_str(name, strlen(name)) % branch_table_sz;
686         struct branch *b = lookup_branch(name);
688         if (b)
689                 die("Invalid attempt to create duplicate branch: %s", name);
690         switch (check_ref_format(name)) {
691         case 0: break; /* its valid */
692         case CHECK_REF_FORMAT_ONELEVEL:
693                 break; /* valid, but too few '/', allow anyway */
694         default:
695                 die("Branch name doesn't conform to GIT standards: %s", name);
696         }
698         b = pool_calloc(1, sizeof(struct branch));
699         b->name = pool_strdup(name);
700         b->table_next_branch = branch_table[hc];
701         b->branch_tree.versions[0].mode = S_IFDIR;
702         b->branch_tree.versions[1].mode = S_IFDIR;
703         b->active = 0;
704         b->pack_id = MAX_PACK_ID;
705         branch_table[hc] = b;
706         branch_count++;
707         return b;
710 static unsigned int hc_entries(unsigned int cnt)
712         cnt = cnt & 7 ? (cnt / 8) + 1 : cnt / 8;
713         return cnt < avail_tree_table_sz ? cnt : avail_tree_table_sz - 1;
716 static struct tree_content *new_tree_content(unsigned int cnt)
718         struct avail_tree_content *f, *l = NULL;
719         struct tree_content *t;
720         unsigned int hc = hc_entries(cnt);
722         for (f = avail_tree_table[hc]; f; l = f, f = f->next_avail)
723                 if (f->entry_capacity >= cnt)
724                         break;
726         if (f) {
727                 if (l)
728                         l->next_avail = f->next_avail;
729                 else
730                         avail_tree_table[hc] = f->next_avail;
731         } else {
732                 cnt = cnt & 7 ? ((cnt / 8) + 1) * 8 : cnt;
733                 f = pool_alloc(sizeof(*t) + sizeof(t->entries[0]) * cnt);
734                 f->entry_capacity = cnt;
735         }
737         t = (struct tree_content*)f;
738         t->entry_count = 0;
739         t->delta_depth = 0;
740         return t;
743 static void release_tree_entry(struct tree_entry *e);
744 static void release_tree_content(struct tree_content *t)
746         struct avail_tree_content *f = (struct avail_tree_content*)t;
747         unsigned int hc = hc_entries(f->entry_capacity);
748         f->next_avail = avail_tree_table[hc];
749         avail_tree_table[hc] = f;
752 static void release_tree_content_recursive(struct tree_content *t)
754         unsigned int i;
755         for (i = 0; i < t->entry_count; i++)
756                 release_tree_entry(t->entries[i]);
757         release_tree_content(t);
760 static struct tree_content *grow_tree_content(
761         struct tree_content *t,
762         int amt)
764         struct tree_content *r = new_tree_content(t->entry_count + amt);
765         r->entry_count = t->entry_count;
766         r->delta_depth = t->delta_depth;
767         memcpy(r->entries,t->entries,t->entry_count*sizeof(t->entries[0]));
768         release_tree_content(t);
769         return r;
772 static struct tree_entry *new_tree_entry(void)
774         struct tree_entry *e;
776         if (!avail_tree_entry) {
777                 unsigned int n = tree_entry_alloc;
778                 total_allocd += n * sizeof(struct tree_entry);
779                 avail_tree_entry = e = xmalloc(n * sizeof(struct tree_entry));
780                 while (n-- > 1) {
781                         *((void**)e) = e + 1;
782                         e++;
783                 }
784                 *((void**)e) = NULL;
785         }
787         e = avail_tree_entry;
788         avail_tree_entry = *((void**)e);
789         return e;
792 static void release_tree_entry(struct tree_entry *e)
794         if (e->tree)
795                 release_tree_content_recursive(e->tree);
796         *((void**)e) = avail_tree_entry;
797         avail_tree_entry = e;
800 static struct tree_content *dup_tree_content(struct tree_content *s)
802         struct tree_content *d;
803         struct tree_entry *a, *b;
804         unsigned int i;
806         if (!s)
807                 return NULL;
808         d = new_tree_content(s->entry_count);
809         for (i = 0; i < s->entry_count; i++) {
810                 a = s->entries[i];
811                 b = new_tree_entry();
812                 memcpy(b, a, sizeof(*a));
813                 if (a->tree && is_null_sha1(b->versions[1].sha1))
814                         b->tree = dup_tree_content(a->tree);
815                 else
816                         b->tree = NULL;
817                 d->entries[i] = b;
818         }
819         d->entry_count = s->entry_count;
820         d->delta_depth = s->delta_depth;
822         return d;
825 static void start_packfile(void)
827         static char tmpfile[PATH_MAX];
828         struct packed_git *p;
829         struct pack_header hdr;
830         int pack_fd;
832         pack_fd = odb_mkstemp(tmpfile, sizeof(tmpfile),
833                               "pack/tmp_pack_XXXXXX");
834         p = xcalloc(1, sizeof(*p) + strlen(tmpfile) + 2);
835         strcpy(p->pack_name, tmpfile);
836         p->pack_fd = pack_fd;
838         hdr.hdr_signature = htonl(PACK_SIGNATURE);
839         hdr.hdr_version = htonl(2);
840         hdr.hdr_entries = 0;
841         write_or_die(p->pack_fd, &hdr, sizeof(hdr));
843         pack_data = p;
844         pack_size = sizeof(hdr);
845         object_count = 0;
847         all_packs = xrealloc(all_packs, sizeof(*all_packs) * (pack_id + 1));
848         all_packs[pack_id] = p;
851 static int oecmp (const void *a_, const void *b_)
853         struct object_entry *a = *((struct object_entry**)a_);
854         struct object_entry *b = *((struct object_entry**)b_);
855         return hashcmp(a->sha1, b->sha1);
858 static char *create_index(void)
860         static char tmpfile[PATH_MAX];
861         git_SHA_CTX ctx;
862         struct sha1file *f;
863         struct object_entry **idx, **c, **last, *e;
864         struct object_entry_pool *o;
865         uint32_t array[256];
866         int i, idx_fd;
868         /* Build the sorted table of object IDs. */
869         idx = xmalloc(object_count * sizeof(struct object_entry*));
870         c = idx;
871         for (o = blocks; o; o = o->next_pool)
872                 for (e = o->next_free; e-- != o->entries;)
873                         if (pack_id == e->pack_id)
874                                 *c++ = e;
875         last = idx + object_count;
876         if (c != last)
877                 die("internal consistency error creating the index");
878         qsort(idx, object_count, sizeof(struct object_entry*), oecmp);
880         /* Generate the fan-out array. */
881         c = idx;
882         for (i = 0; i < 256; i++) {
883                 struct object_entry **next = c;
884                 while (next < last) {
885                         if ((*next)->sha1[0] != i)
886                                 break;
887                         next++;
888                 }
889                 array[i] = htonl(next - idx);
890                 c = next;
891         }
893         idx_fd = odb_mkstemp(tmpfile, sizeof(tmpfile),
894                              "pack/tmp_idx_XXXXXX");
895         f = sha1fd(idx_fd, tmpfile);
896         sha1write(f, array, 256 * sizeof(int));
897         git_SHA1_Init(&ctx);
898         for (c = idx; c != last; c++) {
899                 uint32_t offset = htonl((*c)->offset);
900                 sha1write(f, &offset, 4);
901                 sha1write(f, (*c)->sha1, sizeof((*c)->sha1));
902                 git_SHA1_Update(&ctx, (*c)->sha1, 20);
903         }
904         sha1write(f, pack_data->sha1, sizeof(pack_data->sha1));
905         sha1close(f, NULL, CSUM_FSYNC);
906         free(idx);
907         git_SHA1_Final(pack_data->sha1, &ctx);
908         return tmpfile;
911 static char *keep_pack(char *curr_index_name)
913         static char name[PATH_MAX];
914         static const char *keep_msg = "fast-import";
915         int keep_fd;
917         keep_fd = odb_pack_keep(name, sizeof(name), pack_data->sha1);
918         if (keep_fd < 0)
919                 die_errno("cannot create keep file");
920         write_or_die(keep_fd, keep_msg, strlen(keep_msg));
921         if (close(keep_fd))
922                 die_errno("failed to write keep file");
924         snprintf(name, sizeof(name), "%s/pack/pack-%s.pack",
925                  get_object_directory(), sha1_to_hex(pack_data->sha1));
926         if (move_temp_to_file(pack_data->pack_name, name))
927                 die("cannot store pack file");
929         snprintf(name, sizeof(name), "%s/pack/pack-%s.idx",
930                  get_object_directory(), sha1_to_hex(pack_data->sha1));
931         if (move_temp_to_file(curr_index_name, name))
932                 die("cannot store index file");
933         return name;
936 static void unkeep_all_packs(void)
938         static char name[PATH_MAX];
939         int k;
941         for (k = 0; k < pack_id; k++) {
942                 struct packed_git *p = all_packs[k];
943                 snprintf(name, sizeof(name), "%s/pack/pack-%s.keep",
944                          get_object_directory(), sha1_to_hex(p->sha1));
945                 unlink_or_warn(name);
946         }
949 static void end_packfile(void)
951         struct packed_git *old_p = pack_data, *new_p;
953         clear_delta_base_cache();
954         if (object_count) {
955                 char *idx_name;
956                 int i;
957                 struct branch *b;
958                 struct tag *t;
960                 close_pack_windows(pack_data);
961                 fixup_pack_header_footer(pack_data->pack_fd, pack_data->sha1,
962                                     pack_data->pack_name, object_count,
963                                     NULL, 0);
964                 close(pack_data->pack_fd);
965                 idx_name = keep_pack(create_index());
967                 /* Register the packfile with core git's machinery. */
968                 new_p = add_packed_git(idx_name, strlen(idx_name), 1);
969                 if (!new_p)
970                         die("core git rejected index %s", idx_name);
971                 all_packs[pack_id] = new_p;
972                 install_packed_git(new_p);
974                 /* Print the boundary */
975                 if (pack_edges) {
976                         fprintf(pack_edges, "%s:", new_p->pack_name);
977                         for (i = 0; i < branch_table_sz; i++) {
978                                 for (b = branch_table[i]; b; b = b->table_next_branch) {
979                                         if (b->pack_id == pack_id)
980                                                 fprintf(pack_edges, " %s", sha1_to_hex(b->sha1));
981                                 }
982                         }
983                         for (t = first_tag; t; t = t->next_tag) {
984                                 if (t->pack_id == pack_id)
985                                         fprintf(pack_edges, " %s", sha1_to_hex(t->sha1));
986                         }
987                         fputc('\n', pack_edges);
988                         fflush(pack_edges);
989                 }
991                 pack_id++;
992         }
993         else {
994                 close(old_p->pack_fd);
995                 unlink_or_warn(old_p->pack_name);
996         }
997         free(old_p);
999         /* We can't carry a delta across packfiles. */
1000         strbuf_release(&last_blob.data);
1001         last_blob.offset = 0;
1002         last_blob.depth = 0;
1005 static void cycle_packfile(void)
1007         end_packfile();
1008         start_packfile();
1011 static size_t encode_header(
1012         enum object_type type,
1013         size_t size,
1014         unsigned char *hdr)
1016         int n = 1;
1017         unsigned char c;
1019         if (type < OBJ_COMMIT || type > OBJ_REF_DELTA)
1020                 die("bad type %d", type);
1022         c = (type << 4) | (size & 15);
1023         size >>= 4;
1024         while (size) {
1025                 *hdr++ = c | 0x80;
1026                 c = size & 0x7f;
1027                 size >>= 7;
1028                 n++;
1029         }
1030         *hdr = c;
1031         return n;
1034 static int store_object(
1035         enum object_type type,
1036         struct strbuf *dat,
1037         struct last_object *last,
1038         unsigned char *sha1out,
1039         uintmax_t mark)
1041         void *out, *delta;
1042         struct object_entry *e;
1043         unsigned char hdr[96];
1044         unsigned char sha1[20];
1045         unsigned long hdrlen, deltalen;
1046         git_SHA_CTX c;
1047         z_stream s;
1049         hdrlen = sprintf((char *)hdr,"%s %lu", typename(type),
1050                 (unsigned long)dat->len) + 1;
1051         git_SHA1_Init(&c);
1052         git_SHA1_Update(&c, hdr, hdrlen);
1053         git_SHA1_Update(&c, dat->buf, dat->len);
1054         git_SHA1_Final(sha1, &c);
1055         if (sha1out)
1056                 hashcpy(sha1out, sha1);
1058         e = insert_object(sha1);
1059         if (mark)
1060                 insert_mark(mark, e);
1061         if (e->offset) {
1062                 duplicate_count_by_type[type]++;
1063                 return 1;
1064         } else if (find_sha1_pack(sha1, packed_git)) {
1065                 e->type = type;
1066                 e->pack_id = MAX_PACK_ID;
1067                 e->offset = 1; /* just not zero! */
1068                 duplicate_count_by_type[type]++;
1069                 return 1;
1070         }
1072         if (last && last->data.buf && last->depth < max_depth) {
1073                 delta = diff_delta(last->data.buf, last->data.len,
1074                         dat->buf, dat->len,
1075                         &deltalen, 0);
1076                 if (delta && deltalen >= dat->len) {
1077                         free(delta);
1078                         delta = NULL;
1079                 }
1080         } else
1081                 delta = NULL;
1083         memset(&s, 0, sizeof(s));
1084         deflateInit(&s, pack_compression_level);
1085         if (delta) {
1086                 s.next_in = delta;
1087                 s.avail_in = deltalen;
1088         } else {
1089                 s.next_in = (void *)dat->buf;
1090                 s.avail_in = dat->len;
1091         }
1092         s.avail_out = deflateBound(&s, s.avail_in);
1093         s.next_out = out = xmalloc(s.avail_out);
1094         while (deflate(&s, Z_FINISH) == Z_OK)
1095                 /* nothing */;
1096         deflateEnd(&s);
1098         /* Determine if we should auto-checkpoint. */
1099         if ((pack_size + 60 + s.total_out) > max_packsize
1100                 || (pack_size + 60 + s.total_out) < pack_size) {
1102                 /* This new object needs to *not* have the current pack_id. */
1103                 e->pack_id = pack_id + 1;
1104                 cycle_packfile();
1106                 /* We cannot carry a delta into the new pack. */
1107                 if (delta) {
1108                         free(delta);
1109                         delta = NULL;
1111                         memset(&s, 0, sizeof(s));
1112                         deflateInit(&s, pack_compression_level);
1113                         s.next_in = (void *)dat->buf;
1114                         s.avail_in = dat->len;
1115                         s.avail_out = deflateBound(&s, s.avail_in);
1116                         s.next_out = out = xrealloc(out, s.avail_out);
1117                         while (deflate(&s, Z_FINISH) == Z_OK)
1118                                 /* nothing */;
1119                         deflateEnd(&s);
1120                 }
1121         }
1123         e->type = type;
1124         e->pack_id = pack_id;
1125         e->offset = pack_size;
1126         object_count++;
1127         object_count_by_type[type]++;
1129         if (delta) {
1130                 unsigned long ofs = e->offset - last->offset;
1131                 unsigned pos = sizeof(hdr) - 1;
1133                 delta_count_by_type[type]++;
1134                 e->depth = last->depth + 1;
1136                 hdrlen = encode_header(OBJ_OFS_DELTA, deltalen, hdr);
1137                 write_or_die(pack_data->pack_fd, hdr, hdrlen);
1138                 pack_size += hdrlen;
1140                 hdr[pos] = ofs & 127;
1141                 while (ofs >>= 7)
1142                         hdr[--pos] = 128 | (--ofs & 127);
1143                 write_or_die(pack_data->pack_fd, hdr + pos, sizeof(hdr) - pos);
1144                 pack_size += sizeof(hdr) - pos;
1145         } else {
1146                 e->depth = 0;
1147                 hdrlen = encode_header(type, dat->len, hdr);
1148                 write_or_die(pack_data->pack_fd, hdr, hdrlen);
1149                 pack_size += hdrlen;
1150         }
1152         write_or_die(pack_data->pack_fd, out, s.total_out);
1153         pack_size += s.total_out;
1155         free(out);
1156         free(delta);
1157         if (last) {
1158                 if (last->no_swap) {
1159                         last->data = *dat;
1160                 } else {
1161                         strbuf_swap(&last->data, dat);
1162                 }
1163                 last->offset = e->offset;
1164                 last->depth = e->depth;
1165         }
1166         return 0;
1169 /* All calls must be guarded by find_object() or find_mark() to
1170  * ensure the 'struct object_entry' passed was written by this
1171  * process instance.  We unpack the entry by the offset, avoiding
1172  * the need for the corresponding .idx file.  This unpacking rule
1173  * works because we only use OBJ_REF_DELTA within the packfiles
1174  * created by fast-import.
1175  *
1176  * oe must not be NULL.  Such an oe usually comes from giving
1177  * an unknown SHA-1 to find_object() or an undefined mark to
1178  * find_mark().  Callers must test for this condition and use
1179  * the standard read_sha1_file() when it happens.
1180  *
1181  * oe->pack_id must not be MAX_PACK_ID.  Such an oe is usually from
1182  * find_mark(), where the mark was reloaded from an existing marks
1183  * file and is referencing an object that this fast-import process
1184  * instance did not write out to a packfile.  Callers must test for
1185  * this condition and use read_sha1_file() instead.
1186  */
1187 static void *gfi_unpack_entry(
1188         struct object_entry *oe,
1189         unsigned long *sizep)
1191         enum object_type type;
1192         struct packed_git *p = all_packs[oe->pack_id];
1193         if (p == pack_data && p->pack_size < (pack_size + 20)) {
1194                 /* The object is stored in the packfile we are writing to
1195                  * and we have modified it since the last time we scanned
1196                  * back to read a previously written object.  If an old
1197                  * window covered [p->pack_size, p->pack_size + 20) its
1198                  * data is stale and is not valid.  Closing all windows
1199                  * and updating the packfile length ensures we can read
1200                  * the newly written data.
1201                  */
1202                 close_pack_windows(p);
1204                 /* We have to offer 20 bytes additional on the end of
1205                  * the packfile as the core unpacker code assumes the
1206                  * footer is present at the file end and must promise
1207                  * at least 20 bytes within any window it maps.  But
1208                  * we don't actually create the footer here.
1209                  */
1210                 p->pack_size = pack_size + 20;
1211         }
1212         return unpack_entry(p, oe->offset, &type, sizep);
1215 static const char *get_mode(const char *str, uint16_t *modep)
1217         unsigned char c;
1218         uint16_t mode = 0;
1220         while ((c = *str++) != ' ') {
1221                 if (c < '0' || c > '7')
1222                         return NULL;
1223                 mode = (mode << 3) + (c - '0');
1224         }
1225         *modep = mode;
1226         return str;
1229 static void load_tree(struct tree_entry *root)
1231         unsigned char *sha1 = root->versions[1].sha1;
1232         struct object_entry *myoe;
1233         struct tree_content *t;
1234         unsigned long size;
1235         char *buf;
1236         const char *c;
1238         root->tree = t = new_tree_content(8);
1239         if (is_null_sha1(sha1))
1240                 return;
1242         myoe = find_object(sha1);
1243         if (myoe && myoe->pack_id != MAX_PACK_ID) {
1244                 if (myoe->type != OBJ_TREE)
1245                         die("Not a tree: %s", sha1_to_hex(sha1));
1246                 t->delta_depth = myoe->depth;
1247                 buf = gfi_unpack_entry(myoe, &size);
1248                 if (!buf)
1249                         die("Can't load tree %s", sha1_to_hex(sha1));
1250         } else {
1251                 enum object_type type;
1252                 buf = read_sha1_file(sha1, &type, &size);
1253                 if (!buf || type != OBJ_TREE)
1254                         die("Can't load tree %s", sha1_to_hex(sha1));
1255         }
1257         c = buf;
1258         while (c != (buf + size)) {
1259                 struct tree_entry *e = new_tree_entry();
1261                 if (t->entry_count == t->entry_capacity)
1262                         root->tree = t = grow_tree_content(t, t->entry_count);
1263                 t->entries[t->entry_count++] = e;
1265                 e->tree = NULL;
1266                 c = get_mode(c, &e->versions[1].mode);
1267                 if (!c)
1268                         die("Corrupt mode in %s", sha1_to_hex(sha1));
1269                 e->versions[0].mode = e->versions[1].mode;
1270                 e->name = to_atom(c, strlen(c));
1271                 c += e->name->str_len + 1;
1272                 hashcpy(e->versions[0].sha1, (unsigned char *)c);
1273                 hashcpy(e->versions[1].sha1, (unsigned char *)c);
1274                 c += 20;
1275         }
1276         free(buf);
1279 static int tecmp0 (const void *_a, const void *_b)
1281         struct tree_entry *a = *((struct tree_entry**)_a);
1282         struct tree_entry *b = *((struct tree_entry**)_b);
1283         return base_name_compare(
1284                 a->name->str_dat, a->name->str_len, a->versions[0].mode,
1285                 b->name->str_dat, b->name->str_len, b->versions[0].mode);
1288 static int tecmp1 (const void *_a, const void *_b)
1290         struct tree_entry *a = *((struct tree_entry**)_a);
1291         struct tree_entry *b = *((struct tree_entry**)_b);
1292         return base_name_compare(
1293                 a->name->str_dat, a->name->str_len, a->versions[1].mode,
1294                 b->name->str_dat, b->name->str_len, b->versions[1].mode);
1297 static void mktree(struct tree_content *t, int v, struct strbuf *b)
1299         size_t maxlen = 0;
1300         unsigned int i;
1302         if (!v)
1303                 qsort(t->entries,t->entry_count,sizeof(t->entries[0]),tecmp0);
1304         else
1305                 qsort(t->entries,t->entry_count,sizeof(t->entries[0]),tecmp1);
1307         for (i = 0; i < t->entry_count; i++) {
1308                 if (t->entries[i]->versions[v].mode)
1309                         maxlen += t->entries[i]->name->str_len + 34;
1310         }
1312         strbuf_reset(b);
1313         strbuf_grow(b, maxlen);
1314         for (i = 0; i < t->entry_count; i++) {
1315                 struct tree_entry *e = t->entries[i];
1316                 if (!e->versions[v].mode)
1317                         continue;
1318                 strbuf_addf(b, "%o %s%c", (unsigned int)e->versions[v].mode,
1319                                         e->name->str_dat, '\0');
1320                 strbuf_add(b, e->versions[v].sha1, 20);
1321         }
1324 static void store_tree(struct tree_entry *root)
1326         struct tree_content *t = root->tree;
1327         unsigned int i, j, del;
1328         struct last_object lo = { STRBUF_INIT, 0, 0, /* no_swap */ 1 };
1329         struct object_entry *le;
1331         if (!is_null_sha1(root->versions[1].sha1))
1332                 return;
1334         for (i = 0; i < t->entry_count; i++) {
1335                 if (t->entries[i]->tree)
1336                         store_tree(t->entries[i]);
1337         }
1339         le = find_object(root->versions[0].sha1);
1340         if (S_ISDIR(root->versions[0].mode) && le && le->pack_id == pack_id) {
1341                 mktree(t, 0, &old_tree);
1342                 lo.data = old_tree;
1343                 lo.offset = le->offset;
1344                 lo.depth = t->delta_depth;
1345         }
1347         mktree(t, 1, &new_tree);
1348         store_object(OBJ_TREE, &new_tree, &lo, root->versions[1].sha1, 0);
1350         t->delta_depth = lo.depth;
1351         for (i = 0, j = 0, del = 0; i < t->entry_count; i++) {
1352                 struct tree_entry *e = t->entries[i];
1353                 if (e->versions[1].mode) {
1354                         e->versions[0].mode = e->versions[1].mode;
1355                         hashcpy(e->versions[0].sha1, e->versions[1].sha1);
1356                         t->entries[j++] = e;
1357                 } else {
1358                         release_tree_entry(e);
1359                         del++;
1360                 }
1361         }
1362         t->entry_count -= del;
1365 static int tree_content_set(
1366         struct tree_entry *root,
1367         const char *p,
1368         const unsigned char *sha1,
1369         const uint16_t mode,
1370         struct tree_content *subtree)
1372         struct tree_content *t = root->tree;
1373         const char *slash1;
1374         unsigned int i, n;
1375         struct tree_entry *e;
1377         slash1 = strchr(p, '/');
1378         if (slash1)
1379                 n = slash1 - p;
1380         else
1381                 n = strlen(p);
1382         if (!n)
1383                 die("Empty path component found in input");
1384         if (!slash1 && !S_ISDIR(mode) && subtree)
1385                 die("Non-directories cannot have subtrees");
1387         for (i = 0; i < t->entry_count; i++) {
1388                 e = t->entries[i];
1389                 if (e->name->str_len == n && !strncmp(p, e->name->str_dat, n)) {
1390                         if (!slash1) {
1391                                 if (!S_ISDIR(mode)
1392                                                 && e->versions[1].mode == mode
1393                                                 && !hashcmp(e->versions[1].sha1, sha1))
1394                                         return 0;
1395                                 e->versions[1].mode = mode;
1396                                 hashcpy(e->versions[1].sha1, sha1);
1397                                 if (e->tree)
1398                                         release_tree_content_recursive(e->tree);
1399                                 e->tree = subtree;
1400                                 hashclr(root->versions[1].sha1);
1401                                 return 1;
1402                         }
1403                         if (!S_ISDIR(e->versions[1].mode)) {
1404                                 e->tree = new_tree_content(8);
1405                                 e->versions[1].mode = S_IFDIR;
1406                         }
1407                         if (!e->tree)
1408                                 load_tree(e);
1409                         if (tree_content_set(e, slash1 + 1, sha1, mode, subtree)) {
1410                                 hashclr(root->versions[1].sha1);
1411                                 return 1;
1412                         }
1413                         return 0;
1414                 }
1415         }
1417         if (t->entry_count == t->entry_capacity)
1418                 root->tree = t = grow_tree_content(t, t->entry_count);
1419         e = new_tree_entry();
1420         e->name = to_atom(p, n);
1421         e->versions[0].mode = 0;
1422         hashclr(e->versions[0].sha1);
1423         t->entries[t->entry_count++] = e;
1424         if (slash1) {
1425                 e->tree = new_tree_content(8);
1426                 e->versions[1].mode = S_IFDIR;
1427                 tree_content_set(e, slash1 + 1, sha1, mode, subtree);
1428         } else {
1429                 e->tree = subtree;
1430                 e->versions[1].mode = mode;
1431                 hashcpy(e->versions[1].sha1, sha1);
1432         }
1433         hashclr(root->versions[1].sha1);
1434         return 1;
1437 static int tree_content_remove(
1438         struct tree_entry *root,
1439         const char *p,
1440         struct tree_entry *backup_leaf)
1442         struct tree_content *t = root->tree;
1443         const char *slash1;
1444         unsigned int i, n;
1445         struct tree_entry *e;
1447         slash1 = strchr(p, '/');
1448         if (slash1)
1449                 n = slash1 - p;
1450         else
1451                 n = strlen(p);
1453         for (i = 0; i < t->entry_count; i++) {
1454                 e = t->entries[i];
1455                 if (e->name->str_len == n && !strncmp(p, e->name->str_dat, n)) {
1456                         if (!slash1 || !S_ISDIR(e->versions[1].mode))
1457                                 goto del_entry;
1458                         if (!e->tree)
1459                                 load_tree(e);
1460                         if (tree_content_remove(e, slash1 + 1, backup_leaf)) {
1461                                 for (n = 0; n < e->tree->entry_count; n++) {
1462                                         if (e->tree->entries[n]->versions[1].mode) {
1463                                                 hashclr(root->versions[1].sha1);
1464                                                 return 1;
1465                                         }
1466                                 }
1467                                 backup_leaf = NULL;
1468                                 goto del_entry;
1469                         }
1470                         return 0;
1471                 }
1472         }
1473         return 0;
1475 del_entry:
1476         if (backup_leaf)
1477                 memcpy(backup_leaf, e, sizeof(*backup_leaf));
1478         else if (e->tree)
1479                 release_tree_content_recursive(e->tree);
1480         e->tree = NULL;
1481         e->versions[1].mode = 0;
1482         hashclr(e->versions[1].sha1);
1483         hashclr(root->versions[1].sha1);
1484         return 1;
1487 static int tree_content_get(
1488         struct tree_entry *root,
1489         const char *p,
1490         struct tree_entry *leaf)
1492         struct tree_content *t = root->tree;
1493         const char *slash1;
1494         unsigned int i, n;
1495         struct tree_entry *e;
1497         slash1 = strchr(p, '/');
1498         if (slash1)
1499                 n = slash1 - p;
1500         else
1501                 n = strlen(p);
1503         for (i = 0; i < t->entry_count; i++) {
1504                 e = t->entries[i];
1505                 if (e->name->str_len == n && !strncmp(p, e->name->str_dat, n)) {
1506                         if (!slash1) {
1507                                 memcpy(leaf, e, sizeof(*leaf));
1508                                 if (e->tree && is_null_sha1(e->versions[1].sha1))
1509                                         leaf->tree = dup_tree_content(e->tree);
1510                                 else
1511                                         leaf->tree = NULL;
1512                                 return 1;
1513                         }
1514                         if (!S_ISDIR(e->versions[1].mode))
1515                                 return 0;
1516                         if (!e->tree)
1517                                 load_tree(e);
1518                         return tree_content_get(e, slash1 + 1, leaf);
1519                 }
1520         }
1521         return 0;
1524 static int update_branch(struct branch *b)
1526         static const char *msg = "fast-import";
1527         struct ref_lock *lock;
1528         unsigned char old_sha1[20];
1530         if (is_null_sha1(b->sha1))
1531                 return 0;
1532         if (read_ref(b->name, old_sha1))
1533                 hashclr(old_sha1);
1534         lock = lock_any_ref_for_update(b->name, old_sha1, 0);
1535         if (!lock)
1536                 return error("Unable to lock %s", b->name);
1537         if (!force_update && !is_null_sha1(old_sha1)) {
1538                 struct commit *old_cmit, *new_cmit;
1540                 old_cmit = lookup_commit_reference_gently(old_sha1, 0);
1541                 new_cmit = lookup_commit_reference_gently(b->sha1, 0);
1542                 if (!old_cmit || !new_cmit) {
1543                         unlock_ref(lock);
1544                         return error("Branch %s is missing commits.", b->name);
1545                 }
1547                 if (!in_merge_bases(old_cmit, &new_cmit, 1)) {
1548                         unlock_ref(lock);
1549                         warning("Not updating %s"
1550                                 " (new tip %s does not contain %s)",
1551                                 b->name, sha1_to_hex(b->sha1), sha1_to_hex(old_sha1));
1552                         return -1;
1553                 }
1554         }
1555         if (write_ref_sha1(lock, b->sha1, msg) < 0)
1556                 return error("Unable to update %s", b->name);
1557         return 0;
1560 static void dump_branches(void)
1562         unsigned int i;
1563         struct branch *b;
1565         for (i = 0; i < branch_table_sz; i++) {
1566                 for (b = branch_table[i]; b; b = b->table_next_branch)
1567                         failure |= update_branch(b);
1568         }
1571 static void dump_tags(void)
1573         static const char *msg = "fast-import";
1574         struct tag *t;
1575         struct ref_lock *lock;
1576         char ref_name[PATH_MAX];
1578         for (t = first_tag; t; t = t->next_tag) {
1579                 sprintf(ref_name, "tags/%s", t->name);
1580                 lock = lock_ref_sha1(ref_name, NULL);
1581                 if (!lock || write_ref_sha1(lock, t->sha1, msg) < 0)
1582                         failure |= error("Unable to update %s", ref_name);
1583         }
1586 static void dump_marks_helper(FILE *f,
1587         uintmax_t base,
1588         struct mark_set *m)
1590         uintmax_t k;
1591         if (m->shift) {
1592                 for (k = 0; k < 1024; k++) {
1593                         if (m->data.sets[k])
1594                                 dump_marks_helper(f, (base + k) << m->shift,
1595                                         m->data.sets[k]);
1596                 }
1597         } else {
1598                 for (k = 0; k < 1024; k++) {
1599                         if (m->data.marked[k])
1600                                 fprintf(f, ":%" PRIuMAX " %s\n", base + k,
1601                                         sha1_to_hex(m->data.marked[k]->sha1));
1602                 }
1603         }
1606 static void dump_marks(void)
1608         static struct lock_file mark_lock;
1609         int mark_fd;
1610         FILE *f;
1612         if (!export_marks_file)
1613                 return;
1615         mark_fd = hold_lock_file_for_update(&mark_lock, export_marks_file, 0);
1616         if (mark_fd < 0) {
1617                 failure |= error("Unable to write marks file %s: %s",
1618                         export_marks_file, strerror(errno));
1619                 return;
1620         }
1622         f = fdopen(mark_fd, "w");
1623         if (!f) {
1624                 int saved_errno = errno;
1625                 rollback_lock_file(&mark_lock);
1626                 failure |= error("Unable to write marks file %s: %s",
1627                         export_marks_file, strerror(saved_errno));
1628                 return;
1629         }
1631         /*
1632          * Since the lock file was fdopen()'ed, it should not be close()'ed.
1633          * Assign -1 to the lock file descriptor so that commit_lock_file()
1634          * won't try to close() it.
1635          */
1636         mark_lock.fd = -1;
1638         dump_marks_helper(f, 0, marks);
1639         if (ferror(f) || fclose(f)) {
1640                 int saved_errno = errno;
1641                 rollback_lock_file(&mark_lock);
1642                 failure |= error("Unable to write marks file %s: %s",
1643                         export_marks_file, strerror(saved_errno));
1644                 return;
1645         }
1647         if (commit_lock_file(&mark_lock)) {
1648                 int saved_errno = errno;
1649                 rollback_lock_file(&mark_lock);
1650                 failure |= error("Unable to commit marks file %s: %s",
1651                         export_marks_file, strerror(saved_errno));
1652                 return;
1653         }
1656 static void read_marks(void)
1658         char line[512];
1659         FILE *f = fopen(import_marks_file, "r");
1660         if (!f)
1661                 die_errno("cannot read '%s'", import_marks_file);
1662         while (fgets(line, sizeof(line), f)) {
1663                 uintmax_t mark;
1664                 char *end;
1665                 unsigned char sha1[20];
1666                 struct object_entry *e;
1668                 end = strchr(line, '\n');
1669                 if (line[0] != ':' || !end)
1670                         die("corrupt mark line: %s", line);
1671                 *end = 0;
1672                 mark = strtoumax(line + 1, &end, 10);
1673                 if (!mark || end == line + 1
1674                         || *end != ' ' || get_sha1(end + 1, sha1))
1675                         die("corrupt mark line: %s", line);
1676                 e = find_object(sha1);
1677                 if (!e) {
1678                         enum object_type type = sha1_object_info(sha1, NULL);
1679                         if (type < 0)
1680                                 die("object not found: %s", sha1_to_hex(sha1));
1681                         e = insert_object(sha1);
1682                         e->type = type;
1683                         e->pack_id = MAX_PACK_ID;
1684                         e->offset = 1; /* just not zero! */
1685                 }
1686                 insert_mark(mark, e);
1687         }
1688         fclose(f);
1692 static int read_next_command(void)
1694         static int stdin_eof = 0;
1696         if (stdin_eof) {
1697                 unread_command_buf = 0;
1698                 return EOF;
1699         }
1701         do {
1702                 if (unread_command_buf) {
1703                         unread_command_buf = 0;
1704                 } else {
1705                         struct recent_command *rc;
1707                         strbuf_detach(&command_buf, NULL);
1708                         stdin_eof = strbuf_getline(&command_buf, stdin, '\n');
1709                         if (stdin_eof)
1710                                 return EOF;
1712                         if (!seen_data_command
1713                                 && prefixcmp(command_buf.buf, "feature ")
1714                                 && prefixcmp(command_buf.buf, "option ")) {
1715                                 parse_argv();
1716                         }
1718                         rc = rc_free;
1719                         if (rc)
1720                                 rc_free = rc->next;
1721                         else {
1722                                 rc = cmd_hist.next;
1723                                 cmd_hist.next = rc->next;
1724                                 cmd_hist.next->prev = &cmd_hist;
1725                                 free(rc->buf);
1726                         }
1728                         rc->buf = command_buf.buf;
1729                         rc->prev = cmd_tail;
1730                         rc->next = cmd_hist.prev;
1731                         rc->prev->next = rc;
1732                         cmd_tail = rc;
1733                 }
1734         } while (command_buf.buf[0] == '#');
1736         return 0;
1739 static void skip_optional_lf(void)
1741         int term_char = fgetc(stdin);
1742         if (term_char != '\n' && term_char != EOF)
1743                 ungetc(term_char, stdin);
1746 static void parse_mark(void)
1748         if (!prefixcmp(command_buf.buf, "mark :")) {
1749                 next_mark = strtoumax(command_buf.buf + 6, NULL, 10);
1750                 read_next_command();
1751         }
1752         else
1753                 next_mark = 0;
1756 static void parse_data(struct strbuf *sb)
1758         strbuf_reset(sb);
1760         if (prefixcmp(command_buf.buf, "data "))
1761                 die("Expected 'data n' command, found: %s", command_buf.buf);
1763         if (!prefixcmp(command_buf.buf + 5, "<<")) {
1764                 char *term = xstrdup(command_buf.buf + 5 + 2);
1765                 size_t term_len = command_buf.len - 5 - 2;
1767                 strbuf_detach(&command_buf, NULL);
1768                 for (;;) {
1769                         if (strbuf_getline(&command_buf, stdin, '\n') == EOF)
1770                                 die("EOF in data (terminator '%s' not found)", term);
1771                         if (term_len == command_buf.len
1772                                 && !strcmp(term, command_buf.buf))
1773                                 break;
1774                         strbuf_addbuf(sb, &command_buf);
1775                         strbuf_addch(sb, '\n');
1776                 }
1777                 free(term);
1778         }
1779         else {
1780                 size_t n = 0, length;
1782                 length = strtoul(command_buf.buf + 5, NULL, 10);
1784                 while (n < length) {
1785                         size_t s = strbuf_fread(sb, length - n, stdin);
1786                         if (!s && feof(stdin))
1787                                 die("EOF in data (%lu bytes remaining)",
1788                                         (unsigned long)(length - n));
1789                         n += s;
1790                 }
1791         }
1793         skip_optional_lf();
1796 static int validate_raw_date(const char *src, char *result, int maxlen)
1798         const char *orig_src = src;
1799         char *endp;
1800         unsigned long num;
1802         errno = 0;
1804         num = strtoul(src, &endp, 10);
1805         /* NEEDSWORK: perhaps check for reasonable values? */
1806         if (errno || endp == src || *endp != ' ')
1807                 return -1;
1809         src = endp + 1;
1810         if (*src != '-' && *src != '+')
1811                 return -1;
1813         num = strtoul(src + 1, &endp, 10);
1814         if (errno || endp == src + 1 || *endp || (endp - orig_src) >= maxlen ||
1815             1400 < num)
1816                 return -1;
1818         strcpy(result, orig_src);
1819         return 0;
1822 static char *parse_ident(const char *buf)
1824         const char *gt;
1825         size_t name_len;
1826         char *ident;
1828         gt = strrchr(buf, '>');
1829         if (!gt)
1830                 die("Missing > in ident string: %s", buf);
1831         gt++;
1832         if (*gt != ' ')
1833                 die("Missing space after > in ident string: %s", buf);
1834         gt++;
1835         name_len = gt - buf;
1836         ident = xmalloc(name_len + 24);
1837         strncpy(ident, buf, name_len);
1839         switch (whenspec) {
1840         case WHENSPEC_RAW:
1841                 if (validate_raw_date(gt, ident + name_len, 24) < 0)
1842                         die("Invalid raw date \"%s\" in ident: %s", gt, buf);
1843                 break;
1844         case WHENSPEC_RFC2822:
1845                 if (parse_date(gt, ident + name_len, 24) < 0)
1846                         die("Invalid rfc2822 date \"%s\" in ident: %s", gt, buf);
1847                 break;
1848         case WHENSPEC_NOW:
1849                 if (strcmp("now", gt))
1850                         die("Date in ident must be 'now': %s", buf);
1851                 datestamp(ident + name_len, 24);
1852                 break;
1853         }
1855         return ident;
1858 static void parse_new_blob(void)
1860         static struct strbuf buf = STRBUF_INIT;
1862         read_next_command();
1863         parse_mark();
1864         parse_data(&buf);
1865         store_object(OBJ_BLOB, &buf, &last_blob, NULL, next_mark);
1868 static void unload_one_branch(void)
1870         while (cur_active_branches
1871                 && cur_active_branches >= max_active_branches) {
1872                 uintmax_t min_commit = ULONG_MAX;
1873                 struct branch *e, *l = NULL, *p = NULL;
1875                 for (e = active_branches; e; e = e->active_next_branch) {
1876                         if (e->last_commit < min_commit) {
1877                                 p = l;
1878                                 min_commit = e->last_commit;
1879                         }
1880                         l = e;
1881                 }
1883                 if (p) {
1884                         e = p->active_next_branch;
1885                         p->active_next_branch = e->active_next_branch;
1886                 } else {
1887                         e = active_branches;
1888                         active_branches = e->active_next_branch;
1889                 }
1890                 e->active = 0;
1891                 e->active_next_branch = NULL;
1892                 if (e->branch_tree.tree) {
1893                         release_tree_content_recursive(e->branch_tree.tree);
1894                         e->branch_tree.tree = NULL;
1895                 }
1896                 cur_active_branches--;
1897         }
1900 static void load_branch(struct branch *b)
1902         load_tree(&b->branch_tree);
1903         if (!b->active) {
1904                 b->active = 1;
1905                 b->active_next_branch = active_branches;
1906                 active_branches = b;
1907                 cur_active_branches++;
1908                 branch_load_count++;
1909         }
1912 static void file_change_m(struct branch *b)
1914         const char *p = command_buf.buf + 2;
1915         static struct strbuf uq = STRBUF_INIT;
1916         const char *endp;
1917         struct object_entry *oe = oe;
1918         unsigned char sha1[20];
1919         uint16_t mode, inline_data = 0;
1921         p = get_mode(p, &mode);
1922         if (!p)
1923                 die("Corrupt mode: %s", command_buf.buf);
1924         switch (mode) {
1925         case 0644:
1926         case 0755:
1927                 mode |= S_IFREG;
1928         case S_IFREG | 0644:
1929         case S_IFREG | 0755:
1930         case S_IFLNK:
1931         case S_IFGITLINK:
1932                 /* ok */
1933                 break;
1934         default:
1935                 die("Corrupt mode: %s", command_buf.buf);
1936         }
1938         if (*p == ':') {
1939                 char *x;
1940                 oe = find_mark(strtoumax(p + 1, &x, 10));
1941                 hashcpy(sha1, oe->sha1);
1942                 p = x;
1943         } else if (!prefixcmp(p, "inline")) {
1944                 inline_data = 1;
1945                 p += 6;
1946         } else {
1947                 if (get_sha1_hex(p, sha1))
1948                         die("Invalid SHA1: %s", command_buf.buf);
1949                 oe = find_object(sha1);
1950                 p += 40;
1951         }
1952         if (*p++ != ' ')
1953                 die("Missing space after SHA1: %s", command_buf.buf);
1955         strbuf_reset(&uq);
1956         if (!unquote_c_style(&uq, p, &endp)) {
1957                 if (*endp)
1958                         die("Garbage after path in: %s", command_buf.buf);
1959                 p = uq.buf;
1960         }
1962         if (S_ISGITLINK(mode)) {
1963                 if (inline_data)
1964                         die("Git links cannot be specified 'inline': %s",
1965                                 command_buf.buf);
1966                 else if (oe) {
1967                         if (oe->type != OBJ_COMMIT)
1968                                 die("Not a commit (actually a %s): %s",
1969                                         typename(oe->type), command_buf.buf);
1970                 }
1971                 /*
1972                  * Accept the sha1 without checking; it expected to be in
1973                  * another repository.
1974                  */
1975         } else if (inline_data) {
1976                 static struct strbuf buf = STRBUF_INIT;
1978                 if (p != uq.buf) {
1979                         strbuf_addstr(&uq, p);
1980                         p = uq.buf;
1981                 }
1982                 read_next_command();
1983                 parse_data(&buf);
1984                 store_object(OBJ_BLOB, &buf, &last_blob, sha1, 0);
1985         } else if (oe) {
1986                 if (oe->type != OBJ_BLOB)
1987                         die("Not a blob (actually a %s): %s",
1988                                 typename(oe->type), command_buf.buf);
1989         } else {
1990                 enum object_type type = sha1_object_info(sha1, NULL);
1991                 if (type < 0)
1992                         die("Blob not found: %s", command_buf.buf);
1993                 if (type != OBJ_BLOB)
1994                         die("Not a blob (actually a %s): %s",
1995                             typename(type), command_buf.buf);
1996         }
1998         tree_content_set(&b->branch_tree, p, sha1, mode, NULL);
2001 static void file_change_d(struct branch *b)
2003         const char *p = command_buf.buf + 2;
2004         static struct strbuf uq = STRBUF_INIT;
2005         const char *endp;
2007         strbuf_reset(&uq);
2008         if (!unquote_c_style(&uq, p, &endp)) {
2009                 if (*endp)
2010                         die("Garbage after path in: %s", command_buf.buf);
2011                 p = uq.buf;
2012         }
2013         tree_content_remove(&b->branch_tree, p, NULL);
2016 static void file_change_cr(struct branch *b, int rename)
2018         const char *s, *d;
2019         static struct strbuf s_uq = STRBUF_INIT;
2020         static struct strbuf d_uq = STRBUF_INIT;
2021         const char *endp;
2022         struct tree_entry leaf;
2024         s = command_buf.buf + 2;
2025         strbuf_reset(&s_uq);
2026         if (!unquote_c_style(&s_uq, s, &endp)) {
2027                 if (*endp != ' ')
2028                         die("Missing space after source: %s", command_buf.buf);
2029         } else {
2030                 endp = strchr(s, ' ');
2031                 if (!endp)
2032                         die("Missing space after source: %s", command_buf.buf);
2033                 strbuf_add(&s_uq, s, endp - s);
2034         }
2035         s = s_uq.buf;
2037         endp++;
2038         if (!*endp)
2039                 die("Missing dest: %s", command_buf.buf);
2041         d = endp;
2042         strbuf_reset(&d_uq);
2043         if (!unquote_c_style(&d_uq, d, &endp)) {
2044                 if (*endp)
2045                         die("Garbage after dest in: %s", command_buf.buf);
2046                 d = d_uq.buf;
2047         }
2049         memset(&leaf, 0, sizeof(leaf));
2050         if (rename)
2051                 tree_content_remove(&b->branch_tree, s, &leaf);
2052         else
2053                 tree_content_get(&b->branch_tree, s, &leaf);
2054         if (!leaf.versions[1].mode)
2055                 die("Path %s not in branch", s);
2056         tree_content_set(&b->branch_tree, d,
2057                 leaf.versions[1].sha1,
2058                 leaf.versions[1].mode,
2059                 leaf.tree);
2062 static void note_change_n(struct branch *b)
2064         const char *p = command_buf.buf + 2;
2065         static struct strbuf uq = STRBUF_INIT;
2066         struct object_entry *oe = oe;
2067         struct branch *s;
2068         unsigned char sha1[20], commit_sha1[20];
2069         uint16_t inline_data = 0;
2071         /* <dataref> or 'inline' */
2072         if (*p == ':') {
2073                 char *x;
2074                 oe = find_mark(strtoumax(p + 1, &x, 10));
2075                 hashcpy(sha1, oe->sha1);
2076                 p = x;
2077         } else if (!prefixcmp(p, "inline")) {
2078                 inline_data = 1;
2079                 p += 6;
2080         } else {
2081                 if (get_sha1_hex(p, sha1))
2082                         die("Invalid SHA1: %s", command_buf.buf);
2083                 oe = find_object(sha1);
2084                 p += 40;
2085         }
2086         if (*p++ != ' ')
2087                 die("Missing space after SHA1: %s", command_buf.buf);
2089         /* <committish> */
2090         s = lookup_branch(p);
2091         if (s) {
2092                 hashcpy(commit_sha1, s->sha1);
2093         } else if (*p == ':') {
2094                 uintmax_t commit_mark = strtoumax(p + 1, NULL, 10);
2095                 struct object_entry *commit_oe = find_mark(commit_mark);
2096                 if (commit_oe->type != OBJ_COMMIT)
2097                         die("Mark :%" PRIuMAX " not a commit", commit_mark);
2098                 hashcpy(commit_sha1, commit_oe->sha1);
2099         } else if (!get_sha1(p, commit_sha1)) {
2100                 unsigned long size;
2101                 char *buf = read_object_with_reference(commit_sha1,
2102                         commit_type, &size, commit_sha1);
2103                 if (!buf || size < 46)
2104                         die("Not a valid commit: %s", p);
2105                 free(buf);
2106         } else
2107                 die("Invalid ref name or SHA1 expression: %s", p);
2109         if (inline_data) {
2110                 static struct strbuf buf = STRBUF_INIT;
2112                 if (p != uq.buf) {
2113                         strbuf_addstr(&uq, p);
2114                         p = uq.buf;
2115                 }
2116                 read_next_command();
2117                 parse_data(&buf);
2118                 store_object(OBJ_BLOB, &buf, &last_blob, sha1, 0);
2119         } else if (oe) {
2120                 if (oe->type != OBJ_BLOB)
2121                         die("Not a blob (actually a %s): %s",
2122                                 typename(oe->type), command_buf.buf);
2123         } else {
2124                 enum object_type type = sha1_object_info(sha1, NULL);
2125                 if (type < 0)
2126                         die("Blob not found: %s", command_buf.buf);
2127                 if (type != OBJ_BLOB)
2128                         die("Not a blob (actually a %s): %s",
2129                             typename(type), command_buf.buf);
2130         }
2132         tree_content_set(&b->branch_tree, sha1_to_hex(commit_sha1), sha1,
2133                 S_IFREG | 0644, NULL);
2136 static void file_change_deleteall(struct branch *b)
2138         release_tree_content_recursive(b->branch_tree.tree);
2139         hashclr(b->branch_tree.versions[0].sha1);
2140         hashclr(b->branch_tree.versions[1].sha1);
2141         load_tree(&b->branch_tree);
2144 static void parse_from_commit(struct branch *b, char *buf, unsigned long size)
2146         if (!buf || size < 46)
2147                 die("Not a valid commit: %s", sha1_to_hex(b->sha1));
2148         if (memcmp("tree ", buf, 5)
2149                 || get_sha1_hex(buf + 5, b->branch_tree.versions[1].sha1))
2150                 die("The commit %s is corrupt", sha1_to_hex(b->sha1));
2151         hashcpy(b->branch_tree.versions[0].sha1,
2152                 b->branch_tree.versions[1].sha1);
2155 static void parse_from_existing(struct branch *b)
2157         if (is_null_sha1(b->sha1)) {
2158                 hashclr(b->branch_tree.versions[0].sha1);
2159                 hashclr(b->branch_tree.versions[1].sha1);
2160         } else {
2161                 unsigned long size;
2162                 char *buf;
2164                 buf = read_object_with_reference(b->sha1,
2165                         commit_type, &size, b->sha1);
2166                 parse_from_commit(b, buf, size);
2167                 free(buf);
2168         }
2171 static int parse_from(struct branch *b)
2173         const char *from;
2174         struct branch *s;
2176         if (prefixcmp(command_buf.buf, "from "))
2177                 return 0;
2179         if (b->branch_tree.tree) {
2180                 release_tree_content_recursive(b->branch_tree.tree);
2181                 b->branch_tree.tree = NULL;
2182         }
2184         from = strchr(command_buf.buf, ' ') + 1;
2185         s = lookup_branch(from);
2186         if (b == s)
2187                 die("Can't create a branch from itself: %s", b->name);
2188         else if (s) {
2189                 unsigned char *t = s->branch_tree.versions[1].sha1;
2190                 hashcpy(b->sha1, s->sha1);
2191                 hashcpy(b->branch_tree.versions[0].sha1, t);
2192                 hashcpy(b->branch_tree.versions[1].sha1, t);
2193         } else if (*from == ':') {
2194                 uintmax_t idnum = strtoumax(from + 1, NULL, 10);
2195                 struct object_entry *oe = find_mark(idnum);
2196                 if (oe->type != OBJ_COMMIT)
2197                         die("Mark :%" PRIuMAX " not a commit", idnum);
2198                 hashcpy(b->sha1, oe->sha1);
2199                 if (oe->pack_id != MAX_PACK_ID) {
2200                         unsigned long size;
2201                         char *buf = gfi_unpack_entry(oe, &size);
2202                         parse_from_commit(b, buf, size);
2203                         free(buf);
2204                 } else
2205                         parse_from_existing(b);
2206         } else if (!get_sha1(from, b->sha1))
2207                 parse_from_existing(b);
2208         else
2209                 die("Invalid ref name or SHA1 expression: %s", from);
2211         read_next_command();
2212         return 1;
2215 static struct hash_list *parse_merge(unsigned int *count)
2217         struct hash_list *list = NULL, *n, *e = e;
2218         const char *from;
2219         struct branch *s;
2221         *count = 0;
2222         while (!prefixcmp(command_buf.buf, "merge ")) {
2223                 from = strchr(command_buf.buf, ' ') + 1;
2224                 n = xmalloc(sizeof(*n));
2225                 s = lookup_branch(from);
2226                 if (s)
2227                         hashcpy(n->sha1, s->sha1);
2228                 else if (*from == ':') {
2229                         uintmax_t idnum = strtoumax(from + 1, NULL, 10);
2230                         struct object_entry *oe = find_mark(idnum);
2231                         if (oe->type != OBJ_COMMIT)
2232                                 die("Mark :%" PRIuMAX " not a commit", idnum);
2233                         hashcpy(n->sha1, oe->sha1);
2234                 } else if (!get_sha1(from, n->sha1)) {
2235                         unsigned long size;
2236                         char *buf = read_object_with_reference(n->sha1,
2237                                 commit_type, &size, n->sha1);
2238                         if (!buf || size < 46)
2239                                 die("Not a valid commit: %s", from);
2240                         free(buf);
2241                 } else
2242                         die("Invalid ref name or SHA1 expression: %s", from);
2244                 n->next = NULL;
2245                 if (list)
2246                         e->next = n;
2247                 else
2248                         list = n;
2249                 e = n;
2250                 (*count)++;
2251                 read_next_command();
2252         }
2253         return list;
2256 static void parse_new_commit(void)
2258         static struct strbuf msg = STRBUF_INIT;
2259         struct branch *b;
2260         char *sp;
2261         char *author = NULL;
2262         char *committer = NULL;
2263         struct hash_list *merge_list = NULL;
2264         unsigned int merge_count;
2266         /* Obtain the branch name from the rest of our command */
2267         sp = strchr(command_buf.buf, ' ') + 1;
2268         b = lookup_branch(sp);
2269         if (!b)
2270                 b = new_branch(sp);
2272         read_next_command();
2273         parse_mark();
2274         if (!prefixcmp(command_buf.buf, "author ")) {
2275                 author = parse_ident(command_buf.buf + 7);
2276                 read_next_command();
2277         }
2278         if (!prefixcmp(command_buf.buf, "committer ")) {
2279                 committer = parse_ident(command_buf.buf + 10);
2280                 read_next_command();
2281         }
2282         if (!committer)
2283                 die("Expected committer but didn't get one");
2284         parse_data(&msg);
2285         read_next_command();
2286         parse_from(b);
2287         merge_list = parse_merge(&merge_count);
2289         /* ensure the branch is active/loaded */
2290         if (!b->branch_tree.tree || !max_active_branches) {
2291                 unload_one_branch();
2292                 load_branch(b);
2293         }
2295         /* file_change* */
2296         while (command_buf.len > 0) {
2297                 if (!prefixcmp(command_buf.buf, "M "))
2298                         file_change_m(b);
2299                 else if (!prefixcmp(command_buf.buf, "D "))
2300                         file_change_d(b);
2301                 else if (!prefixcmp(command_buf.buf, "R "))
2302                         file_change_cr(b, 1);
2303                 else if (!prefixcmp(command_buf.buf, "C "))
2304                         file_change_cr(b, 0);
2305                 else if (!prefixcmp(command_buf.buf, "N "))
2306                         note_change_n(b);
2307                 else if (!strcmp("deleteall", command_buf.buf))
2308                         file_change_deleteall(b);
2309                 else {
2310                         unread_command_buf = 1;
2311                         break;
2312                 }
2313                 if (read_next_command() == EOF)
2314                         break;
2315         }
2317         /* build the tree and the commit */
2318         store_tree(&b->branch_tree);
2319         hashcpy(b->branch_tree.versions[0].sha1,
2320                 b->branch_tree.versions[1].sha1);
2322         strbuf_reset(&new_data);
2323         strbuf_addf(&new_data, "tree %s\n",
2324                 sha1_to_hex(b->branch_tree.versions[1].sha1));
2325         if (!is_null_sha1(b->sha1))
2326                 strbuf_addf(&new_data, "parent %s\n", sha1_to_hex(b->sha1));
2327         while (merge_list) {
2328                 struct hash_list *next = merge_list->next;
2329                 strbuf_addf(&new_data, "parent %s\n", sha1_to_hex(merge_list->sha1));
2330                 free(merge_list);
2331                 merge_list = next;
2332         }
2333         strbuf_addf(&new_data,
2334                 "author %s\n"
2335                 "committer %s\n"
2336                 "\n",
2337                 author ? author : committer, committer);
2338         strbuf_addbuf(&new_data, &msg);
2339         free(author);
2340         free(committer);
2342         if (!store_object(OBJ_COMMIT, &new_data, NULL, b->sha1, next_mark))
2343                 b->pack_id = pack_id;
2344         b->last_commit = object_count_by_type[OBJ_COMMIT];
2347 static void parse_new_tag(void)
2349         static struct strbuf msg = STRBUF_INIT;
2350         char *sp;
2351         const char *from;
2352         char *tagger;
2353         struct branch *s;
2354         struct tag *t;
2355         uintmax_t from_mark = 0;
2356         unsigned char sha1[20];
2358         /* Obtain the new tag name from the rest of our command */
2359         sp = strchr(command_buf.buf, ' ') + 1;
2360         t = pool_alloc(sizeof(struct tag));
2361         t->next_tag = NULL;
2362         t->name = pool_strdup(sp);
2363         if (last_tag)
2364                 last_tag->next_tag = t;
2365         else
2366                 first_tag = t;
2367         last_tag = t;
2368         read_next_command();
2370         /* from ... */
2371         if (prefixcmp(command_buf.buf, "from "))
2372                 die("Expected from command, got %s", command_buf.buf);
2373         from = strchr(command_buf.buf, ' ') + 1;
2374         s = lookup_branch(from);
2375         if (s) {
2376                 hashcpy(sha1, s->sha1);
2377         } else if (*from == ':') {
2378                 struct object_entry *oe;
2379                 from_mark = strtoumax(from + 1, NULL, 10);
2380                 oe = find_mark(from_mark);
2381                 if (oe->type != OBJ_COMMIT)
2382                         die("Mark :%" PRIuMAX " not a commit", from_mark);
2383                 hashcpy(sha1, oe->sha1);
2384         } else if (!get_sha1(from, sha1)) {
2385                 unsigned long size;
2386                 char *buf;
2388                 buf = read_object_with_reference(sha1,
2389                         commit_type, &size, sha1);
2390                 if (!buf || size < 46)
2391                         die("Not a valid commit: %s", from);
2392                 free(buf);
2393         } else
2394                 die("Invalid ref name or SHA1 expression: %s", from);
2395         read_next_command();
2397         /* tagger ... */
2398         if (!prefixcmp(command_buf.buf, "tagger ")) {
2399                 tagger = parse_ident(command_buf.buf + 7);
2400                 read_next_command();
2401         } else
2402                 tagger = NULL;
2404         /* tag payload/message */
2405         parse_data(&msg);
2407         /* build the tag object */
2408         strbuf_reset(&new_data);
2410         strbuf_addf(&new_data,
2411                     "object %s\n"
2412                     "type %s\n"
2413                     "tag %s\n",
2414                     sha1_to_hex(sha1), commit_type, t->name);
2415         if (tagger)
2416                 strbuf_addf(&new_data,
2417                             "tagger %s\n", tagger);
2418         strbuf_addch(&new_data, '\n');
2419         strbuf_addbuf(&new_data, &msg);
2420         free(tagger);
2422         if (store_object(OBJ_TAG, &new_data, NULL, t->sha1, 0))
2423                 t->pack_id = MAX_PACK_ID;
2424         else
2425                 t->pack_id = pack_id;
2428 static void parse_reset_branch(void)
2430         struct branch *b;
2431         char *sp;
2433         /* Obtain the branch name from the rest of our command */
2434         sp = strchr(command_buf.buf, ' ') + 1;
2435         b = lookup_branch(sp);
2436         if (b) {
2437                 hashclr(b->sha1);
2438                 hashclr(b->branch_tree.versions[0].sha1);
2439                 hashclr(b->branch_tree.versions[1].sha1);
2440                 if (b->branch_tree.tree) {
2441                         release_tree_content_recursive(b->branch_tree.tree);
2442                         b->branch_tree.tree = NULL;
2443                 }
2444         }
2445         else
2446                 b = new_branch(sp);
2447         read_next_command();
2448         parse_from(b);
2449         if (command_buf.len > 0)
2450                 unread_command_buf = 1;
2453 static void parse_checkpoint(void)
2455         if (object_count) {
2456                 cycle_packfile();
2457                 dump_branches();
2458                 dump_tags();
2459                 dump_marks();
2460         }
2461         skip_optional_lf();
2464 static void parse_progress(void)
2466         fwrite(command_buf.buf, 1, command_buf.len, stdout);
2467         fputc('\n', stdout);
2468         fflush(stdout);
2469         skip_optional_lf();
2472 static void option_import_marks(const char *marks)
2474         import_marks_file = xstrdup(marks);
2477 static void option_date_format(const char *fmt)
2479         if (!strcmp(fmt, "raw"))
2480                 whenspec = WHENSPEC_RAW;
2481         else if (!strcmp(fmt, "rfc2822"))
2482                 whenspec = WHENSPEC_RFC2822;
2483         else if (!strcmp(fmt, "now"))
2484                 whenspec = WHENSPEC_NOW;
2485         else
2486                 die("unknown --date-format argument %s", fmt);
2489 static void option_max_pack_size(const char *packsize)
2491         max_packsize = strtoumax(packsize, NULL, 0) * 1024 * 1024;
2494 static void option_depth(const char *depth)
2496         max_depth = strtoul(depth, NULL, 0);
2497         if (max_depth > MAX_DEPTH)
2498                 die("--depth cannot exceed %u", MAX_DEPTH);
2501 static void option_active_branches(const char *branches)
2503         max_active_branches = strtoul(branches, NULL, 0);
2506 static void option_export_marks(const char *marks)
2508         export_marks_file = xstrdup(marks);
2511 static void option_export_pack_edges(const char *edges)
2513         if (pack_edges)
2514                 fclose(pack_edges);
2515         pack_edges = fopen(edges, "a");
2516         if (!pack_edges)
2517                 die_errno("Cannot open '%s'", edges);
2520 static int parse_one_option(const char *option)
2522         if (!prefixcmp(option, "max-pack-size=")) {
2523                 option_max_pack_size(option + 14);
2524         } else if (!prefixcmp(option, "depth=")) {
2525                 option_depth(option + 6);
2526         } else if (!prefixcmp(option, "active-branches=")) {
2527                 option_active_branches(option + 16);
2528         } else if (!prefixcmp(option, "export-pack-edges=")) {
2529                 option_export_pack_edges(option + 18);
2530         } else if (!prefixcmp(option, "quiet")) {
2531                 show_stats = 0;
2532         } else if (!prefixcmp(option, "stats")) {
2533                 show_stats = 1;
2534         } else {
2535                 return 0;
2536         }
2538         return 1;
2541 static int parse_one_feature(const char *feature)
2543         if (!prefixcmp(feature, "date-format=")) {
2544                 option_date_format(feature + 12);
2545         } else if (!prefixcmp(feature, "import-marks=")) {
2546                 option_import_marks(feature + 13);
2547         } else if (!prefixcmp(feature, "export-marks=")) {
2548                 option_export_marks(feature + 13);
2549         } else if (!prefixcmp(feature, "force")) {
2550                 force_update = 1;
2551         } else {
2552                 return 0;
2553         }
2555         return 1;
2558 static void parse_feature(void)
2560         char *feature = command_buf.buf + 8;
2562         if (seen_data_command)
2563                 die("Got feature command '%s' after data command", feature);
2565         if (parse_one_feature(feature))
2566                 return;
2568         die("This version of fast-import does not support feature %s.", feature);
2571 static void parse_option(void)
2573         char *option = command_buf.buf + 11;
2575         if (seen_data_command)
2576                 die("Got option command '%s' after data command", option);
2578         if (parse_one_option(option))
2579                 return;
2581         die("This version of fast-import does not support option: %s", option);
2584 static int git_pack_config(const char *k, const char *v, void *cb)
2586         if (!strcmp(k, "pack.depth")) {
2587                 max_depth = git_config_int(k, v);
2588                 if (max_depth > MAX_DEPTH)
2589                         max_depth = MAX_DEPTH;
2590                 return 0;
2591         }
2592         if (!strcmp(k, "pack.compression")) {
2593                 int level = git_config_int(k, v);
2594                 if (level == -1)
2595                         level = Z_DEFAULT_COMPRESSION;
2596                 else if (level < 0 || level > Z_BEST_COMPRESSION)
2597                         die("bad pack compression level %d", level);
2598                 pack_compression_level = level;
2599                 pack_compression_seen = 1;
2600                 return 0;
2601         }
2602         return git_default_config(k, v, cb);
2605 static const char fast_import_usage[] =
2606 "git fast-import [--date-format=f] [--max-pack-size=n] [--depth=n] [--active-branches=n] [--export-marks=marks.file]";
2608 static void parse_argv(void)
2610         unsigned int i;
2612         for (i = 1; i < global_argc; i++) {
2613                 const char *a = global_argv[i];
2615                 if (*a != '-' || !strcmp(a, "--"))
2616                         break;
2618                 if (parse_one_option(a + 2))
2619                         continue;
2621                 if (parse_one_feature(a + 2))
2622                         continue;
2624                 die("unknown option %s", a);
2625         }
2626         if (i != global_argc)
2627                 usage(fast_import_usage);
2629         seen_data_command = 1;
2630         if (import_marks_file)
2631                 read_marks();
2634 int main(int argc, const char **argv)
2636         unsigned int i;
2638         git_extract_argv0_path(argv[0]);
2640         if (argc == 2 && !strcmp(argv[1], "-h"))
2641                 usage(fast_import_usage);
2643         setup_git_directory();
2644         git_config(git_pack_config, NULL);
2645         if (!pack_compression_seen && core_compression_seen)
2646                 pack_compression_level = core_compression_level;
2648         alloc_objects(object_entry_alloc);
2649         strbuf_init(&command_buf, 0);
2650         atom_table = xcalloc(atom_table_sz, sizeof(struct atom_str*));
2651         branch_table = xcalloc(branch_table_sz, sizeof(struct branch*));
2652         avail_tree_table = xcalloc(avail_tree_table_sz, sizeof(struct avail_tree_content*));
2653         marks = pool_calloc(1, sizeof(struct mark_set));
2655         global_argc = argc;
2656         global_argv = argv;
2658         rc_free = pool_alloc(cmd_save * sizeof(*rc_free));
2659         for (i = 0; i < (cmd_save - 1); i++)
2660                 rc_free[i].next = &rc_free[i + 1];
2661         rc_free[cmd_save - 1].next = NULL;
2663         prepare_packed_git();
2664         start_packfile();
2665         set_die_routine(die_nicely);
2666         while (read_next_command() != EOF) {
2667                 if (!strcmp("blob", command_buf.buf))
2668                         parse_new_blob();
2669                 else if (!prefixcmp(command_buf.buf, "commit "))
2670                         parse_new_commit();
2671                 else if (!prefixcmp(command_buf.buf, "tag "))
2672                         parse_new_tag();
2673                 else if (!prefixcmp(command_buf.buf, "reset "))
2674                         parse_reset_branch();
2675                 else if (!strcmp("checkpoint", command_buf.buf))
2676                         parse_checkpoint();
2677                 else if (!prefixcmp(command_buf.buf, "progress "))
2678                         parse_progress();
2679                 else if (!prefixcmp(command_buf.buf, "feature "))
2680                         parse_feature();
2681                 else if (!prefixcmp(command_buf.buf, "option git "))
2682                         parse_option();
2683                 else if (!prefixcmp(command_buf.buf, "option "))
2684                         /* ignore non-git options*/;
2685                 else
2686                         die("Unsupported command: %s", command_buf.buf);
2687         }
2689         /* argv hasn't been parsed yet, do so */
2690         if (!seen_data_command)
2691                 parse_argv();
2693         end_packfile();
2695         dump_branches();
2696         dump_tags();
2697         unkeep_all_packs();
2698         dump_marks();
2700         if (pack_edges)
2701                 fclose(pack_edges);
2703         if (show_stats) {
2704                 uintmax_t total_count = 0, duplicate_count = 0;
2705                 for (i = 0; i < ARRAY_SIZE(object_count_by_type); i++)
2706                         total_count += object_count_by_type[i];
2707                 for (i = 0; i < ARRAY_SIZE(duplicate_count_by_type); i++)
2708                         duplicate_count += duplicate_count_by_type[i];
2710                 fprintf(stderr, "%s statistics:\n", argv[0]);
2711                 fprintf(stderr, "---------------------------------------------------------------------\n");
2712                 fprintf(stderr, "Alloc'd objects: %10" PRIuMAX "\n", alloc_count);
2713                 fprintf(stderr, "Total objects:   %10" PRIuMAX " (%10" PRIuMAX " duplicates                  )\n", total_count, duplicate_count);
2714                 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]);
2715                 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]);
2716                 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]);
2717                 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]);
2718                 fprintf(stderr, "Total branches:  %10lu (%10lu loads     )\n", branch_count, branch_load_count);
2719                 fprintf(stderr, "      marks:     %10" PRIuMAX " (%10" PRIuMAX " unique    )\n", (((uintmax_t)1) << marks->shift) * 1024, marks_set_count);
2720                 fprintf(stderr, "      atoms:     %10u\n", atom_cnt);
2721                 fprintf(stderr, "Memory total:    %10" PRIuMAX " KiB\n", (total_allocd + alloc_count*sizeof(struct object_entry))/1024);
2722                 fprintf(stderr, "       pools:    %10lu KiB\n", (unsigned long)(total_allocd/1024));
2723                 fprintf(stderr, "     objects:    %10" PRIuMAX " KiB\n", (alloc_count*sizeof(struct object_entry))/1024);
2724                 fprintf(stderr, "---------------------------------------------------------------------\n");
2725                 pack_report();
2726                 fprintf(stderr, "---------------------------------------------------------------------\n");
2727                 fprintf(stderr, "\n");
2728         }
2730         return failure ? 1 : 0;