tree.h API: simplify read_tree_recursive() signature
[git] / archive.c
1 #include "cache.h"
2 #include "config.h"
3 #include "refs.h"
4 #include "object-store.h"
5 #include "commit.h"
6 #include "tree-walk.h"
7 #include "attr.h"
8 #include "archive.h"
9 #include "parse-options.h"
10 #include "unpack-trees.h"
11 #include "dir.h"
12
13 static char const * const archive_usage[] = {
14         N_("git archive [<options>] <tree-ish> [<path>...]"),
15         N_("git archive --list"),
16         N_("git archive --remote <repo> [--exec <cmd>] [<options>] <tree-ish> [<path>...]"),
17         N_("git archive --remote <repo> [--exec <cmd>] --list"),
18         NULL
19 };
20
21 static const struct archiver **archivers;
22 static int nr_archivers;
23 static int alloc_archivers;
24 static int remote_allow_unreachable;
25
26 void register_archiver(struct archiver *ar)
27 {
28         ALLOC_GROW(archivers, nr_archivers + 1, alloc_archivers);
29         archivers[nr_archivers++] = ar;
30 }
31
32 void init_archivers(void)
33 {
34         init_tar_archiver();
35         init_zip_archiver();
36 }
37
38 static void format_subst(const struct commit *commit,
39                          const char *src, size_t len,
40                          struct strbuf *buf)
41 {
42         char *to_free = NULL;
43         struct strbuf fmt = STRBUF_INIT;
44         struct pretty_print_context ctx = {0};
45         ctx.date_mode.type = DATE_NORMAL;
46         ctx.abbrev = DEFAULT_ABBREV;
47
48         if (src == buf->buf)
49                 to_free = strbuf_detach(buf, NULL);
50         for (;;) {
51                 const char *b, *c;
52
53                 b = memmem(src, len, "$Format:", 8);
54                 if (!b)
55                         break;
56                 c = memchr(b + 8, '$', (src + len) - b - 8);
57                 if (!c)
58                         break;
59
60                 strbuf_reset(&fmt);
61                 strbuf_add(&fmt, b + 8, c - b - 8);
62
63                 strbuf_add(buf, src, b - src);
64                 format_commit_message(commit, fmt.buf, buf, &ctx);
65                 len -= c + 1 - src;
66                 src  = c + 1;
67         }
68         strbuf_add(buf, src, len);
69         strbuf_release(&fmt);
70         free(to_free);
71 }
72
73 static void *object_file_to_archive(const struct archiver_args *args,
74                                     const char *path,
75                                     const struct object_id *oid,
76                                     unsigned int mode,
77                                     enum object_type *type,
78                                     unsigned long *sizep)
79 {
80         void *buffer;
81         const struct commit *commit = args->convert ? args->commit : NULL;
82         struct checkout_metadata meta;
83
84         init_checkout_metadata(&meta, args->refname,
85                                args->commit_oid ? args->commit_oid :
86                                (args->tree ? &args->tree->object.oid : NULL), oid);
87
88         path += args->baselen;
89         buffer = read_object_file(oid, type, sizep);
90         if (buffer && S_ISREG(mode)) {
91                 struct strbuf buf = STRBUF_INIT;
92                 size_t size = 0;
93
94                 strbuf_attach(&buf, buffer, *sizep, *sizep + 1);
95                 convert_to_working_tree(args->repo->index, path, buf.buf, buf.len, &buf, &meta);
96                 if (commit)
97                         format_subst(commit, buf.buf, buf.len, &buf);
98                 buffer = strbuf_detach(&buf, &size);
99                 *sizep = size;
100         }
101
102         return buffer;
103 }
104
105 struct directory {
106         struct directory *up;
107         struct object_id oid;
108         int baselen, len;
109         unsigned mode;
110         char path[FLEX_ARRAY];
111 };
112
113 struct archiver_context {
114         struct archiver_args *args;
115         write_archive_entry_fn_t write_entry;
116         struct directory *bottom;
117 };
118
119 static const struct attr_check *get_archive_attrs(struct index_state *istate,
120                                                   const char *path)
121 {
122         static struct attr_check *check;
123         if (!check)
124                 check = attr_check_initl("export-ignore", "export-subst", NULL);
125         git_check_attr(istate, path, check);
126         return check;
127 }
128
129 static int check_attr_export_ignore(const struct attr_check *check)
130 {
131         return check && ATTR_TRUE(check->items[0].value);
132 }
133
134 static int check_attr_export_subst(const struct attr_check *check)
135 {
136         return check && ATTR_TRUE(check->items[1].value);
137 }
138
139 static int write_archive_entry(const struct object_id *oid, const char *base,
140                 int baselen, const char *filename, unsigned mode,
141                 void *context)
142 {
143         static struct strbuf path = STRBUF_INIT;
144         struct archiver_context *c = context;
145         struct archiver_args *args = c->args;
146         write_archive_entry_fn_t write_entry = c->write_entry;
147         int err;
148         const char *path_without_prefix;
149         unsigned long size;
150         void *buffer;
151         enum object_type type;
152
153         args->convert = 0;
154         strbuf_reset(&path);
155         strbuf_grow(&path, PATH_MAX);
156         strbuf_add(&path, args->base, args->baselen);
157         strbuf_add(&path, base, baselen);
158         strbuf_addstr(&path, filename);
159         if (S_ISDIR(mode) || S_ISGITLINK(mode))
160                 strbuf_addch(&path, '/');
161         path_without_prefix = path.buf + args->baselen;
162
163         if (!S_ISDIR(mode)) {
164                 const struct attr_check *check;
165                 check = get_archive_attrs(args->repo->index, path_without_prefix);
166                 if (check_attr_export_ignore(check))
167                         return 0;
168                 args->convert = check_attr_export_subst(check);
169         }
170
171         if (S_ISDIR(mode) || S_ISGITLINK(mode)) {
172                 if (args->verbose)
173                         fprintf(stderr, "%.*s\n", (int)path.len, path.buf);
174                 err = write_entry(args, oid, path.buf, path.len, mode, NULL, 0);
175                 if (err)
176                         return err;
177                 return (S_ISDIR(mode) ? READ_TREE_RECURSIVE : 0);
178         }
179
180         if (args->verbose)
181                 fprintf(stderr, "%.*s\n", (int)path.len, path.buf);
182
183         /* Stream it? */
184         if (S_ISREG(mode) && !args->convert &&
185             oid_object_info(args->repo, oid, &size) == OBJ_BLOB &&
186             size > big_file_threshold)
187                 return write_entry(args, oid, path.buf, path.len, mode, NULL, size);
188
189         buffer = object_file_to_archive(args, path.buf, oid, mode, &type, &size);
190         if (!buffer)
191                 return error(_("cannot read %s"), oid_to_hex(oid));
192         err = write_entry(args, oid, path.buf, path.len, mode, buffer, size);
193         free(buffer);
194         return err;
195 }
196
197 static void queue_directory(const unsigned char *sha1,
198                 struct strbuf *base, const char *filename,
199                 unsigned mode, struct archiver_context *c)
200 {
201         struct directory *d;
202         size_t len = st_add4(base->len, 1, strlen(filename), 1);
203         d = xmalloc(st_add(sizeof(*d), len));
204         d->up      = c->bottom;
205         d->baselen = base->len;
206         d->mode    = mode;
207         c->bottom  = d;
208         d->len = xsnprintf(d->path, len, "%.*s%s/", (int)base->len, base->buf, filename);
209         hashcpy(d->oid.hash, sha1);
210 }
211
212 static int write_directory(struct archiver_context *c)
213 {
214         struct directory *d = c->bottom;
215         int ret;
216
217         if (!d)
218                 return 0;
219         c->bottom = d->up;
220         d->path[d->len - 1] = '\0'; /* no trailing slash */
221         ret =
222                 write_directory(c) ||
223                 write_archive_entry(&d->oid, d->path, d->baselen,
224                                     d->path + d->baselen, d->mode,
225                                     c) != READ_TREE_RECURSIVE;
226         free(d);
227         return ret ? -1 : 0;
228 }
229
230 static int queue_or_write_archive_entry(const struct object_id *oid,
231                 struct strbuf *base, const char *filename,
232                 unsigned mode, void *context)
233 {
234         struct archiver_context *c = context;
235
236         while (c->bottom &&
237                !(base->len >= c->bottom->len &&
238                  !strncmp(base->buf, c->bottom->path, c->bottom->len))) {
239                 struct directory *next = c->bottom->up;
240                 free(c->bottom);
241                 c->bottom = next;
242         }
243
244         if (S_ISDIR(mode)) {
245                 size_t baselen = base->len;
246                 const struct attr_check *check;
247
248                 /* Borrow base, but restore its original value when done. */
249                 strbuf_addstr(base, filename);
250                 strbuf_addch(base, '/');
251                 check = get_archive_attrs(c->args->repo->index, base->buf);
252                 strbuf_setlen(base, baselen);
253
254                 if (check_attr_export_ignore(check))
255                         return 0;
256                 queue_directory(oid->hash, base, filename,
257                                 mode, c);
258                 return READ_TREE_RECURSIVE;
259         }
260
261         if (write_directory(c))
262                 return -1;
263         return write_archive_entry(oid, base->buf, base->len, filename, mode,
264                                    context);
265 }
266
267 struct extra_file_info {
268         char *base;
269         struct stat stat;
270 };
271
272 int write_archive_entries(struct archiver_args *args,
273                 write_archive_entry_fn_t write_entry)
274 {
275         struct archiver_context context;
276         struct unpack_trees_options opts;
277         struct tree_desc t;
278         int err;
279         struct strbuf path_in_archive = STRBUF_INIT;
280         struct strbuf content = STRBUF_INIT;
281         struct object_id fake_oid = null_oid;
282         int i;
283
284         if (args->baselen > 0 && args->base[args->baselen - 1] == '/') {
285                 size_t len = args->baselen;
286
287                 while (len > 1 && args->base[len - 2] == '/')
288                         len--;
289                 if (args->verbose)
290                         fprintf(stderr, "%.*s\n", (int)len, args->base);
291                 err = write_entry(args, &args->tree->object.oid, args->base,
292                                   len, 040777, NULL, 0);
293                 if (err)
294                         return err;
295         }
296
297         memset(&context, 0, sizeof(context));
298         context.args = args;
299         context.write_entry = write_entry;
300
301         /*
302          * Setup index and instruct attr to read index only
303          */
304         if (!args->worktree_attributes) {
305                 memset(&opts, 0, sizeof(opts));
306                 opts.index_only = 1;
307                 opts.head_idx = -1;
308                 opts.src_index = args->repo->index;
309                 opts.dst_index = args->repo->index;
310                 opts.fn = oneway_merge;
311                 init_tree_desc(&t, args->tree->buffer, args->tree->size);
312                 if (unpack_trees(1, &t, &opts))
313                         return -1;
314                 git_attr_set_direction(GIT_ATTR_INDEX);
315         }
316
317         err = read_tree(args->repo, args->tree,
318                         &args->pathspec,
319                         queue_or_write_archive_entry,
320                         &context);
321         if (err == READ_TREE_RECURSIVE)
322                 err = 0;
323         while (context.bottom) {
324                 struct directory *next = context.bottom->up;
325                 free(context.bottom);
326                 context.bottom = next;
327         }
328
329         for (i = 0; i < args->extra_files.nr; i++) {
330                 struct string_list_item *item = args->extra_files.items + i;
331                 char *path = item->string;
332                 struct extra_file_info *info = item->util;
333
334                 put_be64(fake_oid.hash, i + 1);
335
336                 strbuf_reset(&path_in_archive);
337                 if (info->base)
338                         strbuf_addstr(&path_in_archive, info->base);
339                 strbuf_addstr(&path_in_archive, basename(path));
340
341                 strbuf_reset(&content);
342                 if (strbuf_read_file(&content, path, info->stat.st_size) < 0)
343                         err = error_errno(_("could not read '%s'"), path);
344                 else
345                         err = write_entry(args, &fake_oid, path_in_archive.buf,
346                                           path_in_archive.len,
347                                           info->stat.st_mode,
348                                           content.buf, content.len);
349                 if (err)
350                         break;
351         }
352         strbuf_release(&path_in_archive);
353         strbuf_release(&content);
354
355         return err;
356 }
357
358 static const struct archiver *lookup_archiver(const char *name)
359 {
360         int i;
361
362         if (!name)
363                 return NULL;
364
365         for (i = 0; i < nr_archivers; i++) {
366                 if (!strcmp(name, archivers[i]->name))
367                         return archivers[i];
368         }
369         return NULL;
370 }
371
372 struct path_exists_context {
373         struct pathspec pathspec;
374         struct archiver_args *args;
375 };
376
377 static int reject_entry(const struct object_id *oid, struct strbuf *base,
378                         const char *filename, unsigned mode,
379                         void *context)
380 {
381         int ret = -1;
382         struct path_exists_context *ctx = context;
383
384         if (S_ISDIR(mode)) {
385                 struct strbuf sb = STRBUF_INIT;
386                 strbuf_addbuf(&sb, base);
387                 strbuf_addstr(&sb, filename);
388                 if (!match_pathspec(ctx->args->repo->index,
389                                     &ctx->pathspec,
390                                     sb.buf, sb.len, 0, NULL, 1))
391                         ret = READ_TREE_RECURSIVE;
392                 strbuf_release(&sb);
393         }
394         return ret;
395 }
396
397 static int path_exists(struct archiver_args *args, const char *path)
398 {
399         const char *paths[] = { path, NULL };
400         struct path_exists_context ctx;
401         int ret;
402
403         ctx.args = args;
404         parse_pathspec(&ctx.pathspec, 0, 0, "", paths);
405         ctx.pathspec.recursive = 1;
406         ret = read_tree(args->repo, args->tree,
407                         &ctx.pathspec,
408                         reject_entry, &ctx);
409         clear_pathspec(&ctx.pathspec);
410         return ret != 0;
411 }
412
413 static void parse_pathspec_arg(const char **pathspec,
414                 struct archiver_args *ar_args)
415 {
416         /*
417          * must be consistent with parse_pathspec in path_exists()
418          * Also if pathspec patterns are dependent, we're in big
419          * trouble as we test each one separately
420          */
421         parse_pathspec(&ar_args->pathspec, 0,
422                        PATHSPEC_PREFER_FULL,
423                        "", pathspec);
424         ar_args->pathspec.recursive = 1;
425         if (pathspec) {
426                 while (*pathspec) {
427                         if (**pathspec && !path_exists(ar_args, *pathspec))
428                                 die(_("pathspec '%s' did not match any files"), *pathspec);
429                         pathspec++;
430                 }
431         }
432 }
433
434 static void parse_treeish_arg(const char **argv,
435                 struct archiver_args *ar_args, const char *prefix,
436                 int remote)
437 {
438         const char *name = argv[0];
439         const struct object_id *commit_oid;
440         time_t archive_time;
441         struct tree *tree;
442         const struct commit *commit;
443         struct object_id oid;
444         char *ref = NULL;
445
446         /* Remotes are only allowed to fetch actual refs */
447         if (remote && !remote_allow_unreachable) {
448                 const char *colon = strchrnul(name, ':');
449                 int refnamelen = colon - name;
450
451                 if (!dwim_ref(name, refnamelen, &oid, &ref, 0))
452                         die(_("no such ref: %.*s"), refnamelen, name);
453         } else {
454                 dwim_ref(name, strlen(name), &oid, &ref, 0);
455         }
456
457         if (get_oid(name, &oid))
458                 die(_("not a valid object name: %s"), name);
459
460         commit = lookup_commit_reference_gently(ar_args->repo, &oid, 1);
461         if (commit) {
462                 commit_oid = &commit->object.oid;
463                 archive_time = commit->date;
464         } else {
465                 commit_oid = NULL;
466                 archive_time = time(NULL);
467         }
468
469         tree = parse_tree_indirect(&oid);
470         if (tree == NULL)
471                 die(_("not a tree object: %s"), oid_to_hex(&oid));
472
473         if (prefix) {
474                 struct object_id tree_oid;
475                 unsigned short mode;
476                 int err;
477
478                 err = get_tree_entry(ar_args->repo,
479                                      &tree->object.oid,
480                                      prefix, &tree_oid,
481                                      &mode);
482                 if (err || !S_ISDIR(mode))
483                         die(_("current working directory is untracked"));
484
485                 tree = parse_tree_indirect(&tree_oid);
486         }
487         ar_args->refname = ref;
488         ar_args->tree = tree;
489         ar_args->commit_oid = commit_oid;
490         ar_args->commit = commit;
491         ar_args->time = archive_time;
492 }
493
494 static void extra_file_info_clear(void *util, const char *str)
495 {
496         struct extra_file_info *info = util;
497         free(info->base);
498         free(info);
499 }
500
501 static int add_file_cb(const struct option *opt, const char *arg, int unset)
502 {
503         struct archiver_args *args = opt->value;
504         const char **basep = (const char **)opt->defval;
505         const char *base = *basep;
506         char *path;
507         struct string_list_item *item;
508         struct extra_file_info *info;
509
510         if (unset) {
511                 string_list_clear_func(&args->extra_files,
512                                        extra_file_info_clear);
513                 return 0;
514         }
515
516         if (!arg)
517                 return -1;
518
519         path = prefix_filename(args->prefix, arg);
520         item = string_list_append_nodup(&args->extra_files, path);
521         item->util = info = xmalloc(sizeof(*info));
522         info->base = xstrdup_or_null(base);
523         if (stat(path, &info->stat))
524                 die(_("File not found: %s"), path);
525         if (!S_ISREG(info->stat.st_mode))
526                 die(_("Not a regular file: %s"), path);
527         return 0;
528 }
529
530 static int number_callback(const struct option *opt, const char *arg, int unset)
531 {
532         BUG_ON_OPT_NEG(unset);
533         *(int *)opt->value = strtol(arg, NULL, 10);
534         return 0;
535 }
536
537 static int parse_archive_args(int argc, const char **argv,
538                 const struct archiver **ar, struct archiver_args *args,
539                 const char *name_hint, int is_remote)
540 {
541         const char *format = NULL;
542         const char *base = NULL;
543         const char *remote = NULL;
544         const char *exec = NULL;
545         const char *output = NULL;
546         int compression_level = -1;
547         int verbose = 0;
548         int i;
549         int list = 0;
550         int worktree_attributes = 0;
551         struct option opts[] = {
552                 OPT_GROUP(""),
553                 OPT_STRING(0, "format", &format, N_("fmt"), N_("archive format")),
554                 OPT_STRING(0, "prefix", &base, N_("prefix"),
555                         N_("prepend prefix to each pathname in the archive")),
556                 { OPTION_CALLBACK, 0, "add-file", args, N_("file"),
557                   N_("add untracked file to archive"), 0, add_file_cb,
558                   (intptr_t)&base },
559                 OPT_STRING('o', "output", &output, N_("file"),
560                         N_("write the archive to this file")),
561                 OPT_BOOL(0, "worktree-attributes", &worktree_attributes,
562                         N_("read .gitattributes in working directory")),
563                 OPT__VERBOSE(&verbose, N_("report archived files on stderr")),
564                 OPT_NUMBER_CALLBACK(&compression_level,
565                         N_("set compression level"), number_callback),
566                 OPT_GROUP(""),
567                 OPT_BOOL('l', "list", &list,
568                         N_("list supported archive formats")),
569                 OPT_GROUP(""),
570                 OPT_STRING(0, "remote", &remote, N_("repo"),
571                         N_("retrieve the archive from remote repository <repo>")),
572                 OPT_STRING(0, "exec", &exec, N_("command"),
573                         N_("path to the remote git-upload-archive command")),
574                 OPT_END()
575         };
576
577         argc = parse_options(argc, argv, NULL, opts, archive_usage, 0);
578
579         if (remote)
580                 die(_("Unexpected option --remote"));
581         if (exec)
582                 die(_("Option --exec can only be used together with --remote"));
583         if (output)
584                 die(_("Unexpected option --output"));
585         if (is_remote && args->extra_files.nr)
586                 die(_("Options --add-file and --remote cannot be used together"));
587
588         if (!base)
589                 base = "";
590
591         if (list) {
592                 for (i = 0; i < nr_archivers; i++)
593                         if (!is_remote || archivers[i]->flags & ARCHIVER_REMOTE)
594                                 printf("%s\n", archivers[i]->name);
595                 exit(0);
596         }
597
598         if (!format && name_hint)
599                 format = archive_format_from_filename(name_hint);
600         if (!format)
601                 format = "tar";
602
603         /* We need at least one parameter -- tree-ish */
604         if (argc < 1)
605                 usage_with_options(archive_usage, opts);
606         *ar = lookup_archiver(format);
607         if (!*ar || (is_remote && !((*ar)->flags & ARCHIVER_REMOTE)))
608                 die(_("Unknown archive format '%s'"), format);
609
610         args->compression_level = Z_DEFAULT_COMPRESSION;
611         if (compression_level != -1) {
612                 int levels_ok = (*ar)->flags & ARCHIVER_WANT_COMPRESSION_LEVELS;
613                 int high_ok = (*ar)->flags & ARCHIVER_HIGH_COMPRESSION_LEVELS;
614                 if (levels_ok && (compression_level <= 9 || high_ok))
615                         args->compression_level = compression_level;
616                 else {
617                         die(_("Argument not supported for format '%s': -%d"),
618                                         format, compression_level);
619                 }
620         }
621         args->verbose = verbose;
622         args->base = base;
623         args->baselen = strlen(base);
624         args->worktree_attributes = worktree_attributes;
625
626         return argc;
627 }
628
629 int write_archive(int argc, const char **argv, const char *prefix,
630                   struct repository *repo,
631                   const char *name_hint, int remote)
632 {
633         const struct archiver *ar = NULL;
634         struct archiver_args args;
635         int rc;
636
637         git_config_get_bool("uploadarchive.allowunreachable", &remote_allow_unreachable);
638         git_config(git_default_config, NULL);
639
640         args.repo = repo;
641         args.prefix = prefix;
642         string_list_init(&args.extra_files, 1);
643         argc = parse_archive_args(argc, argv, &ar, &args, name_hint, remote);
644         if (!startup_info->have_repository) {
645                 /*
646                  * We know this will die() with an error, so we could just
647                  * die ourselves; but its error message will be more specific
648                  * than what we could write here.
649                  */
650                 setup_git_directory();
651         }
652
653         parse_treeish_arg(argv, &args, prefix, remote);
654         parse_pathspec_arg(argv + 1, &args);
655
656         rc = ar->write_archive(ar, &args);
657
658         string_list_clear_func(&args.extra_files, extra_file_info_clear);
659         free(args.refname);
660
661         return rc;
662 }
663
664 static int match_extension(const char *filename, const char *ext)
665 {
666         int prefixlen = strlen(filename) - strlen(ext);
667
668         /*
669          * We need 1 character for the '.', and 1 character to ensure that the
670          * prefix is non-empty (k.e., we don't match .tar.gz with no actual
671          * filename).
672          */
673         if (prefixlen < 2 || filename[prefixlen - 1] != '.')
674                 return 0;
675         return !strcmp(filename + prefixlen, ext);
676 }
677
678 const char *archive_format_from_filename(const char *filename)
679 {
680         int i;
681
682         for (i = 0; i < nr_archivers; i++)
683                 if (match_extension(filename, archivers[i]->name))
684                         return archivers[i]->name;
685         return NULL;
686 }