rebase -i: remove patch file after conflict resolution
[git.git] / archive.c
blobf1b8e9ce486e380367045b42bc1c470f20bcf29e
1 #include "git-compat-util.h"
2 #include "abspath.h"
3 #include "alloc.h"
4 #include "config.h"
5 #include "environment.h"
6 #include "gettext.h"
7 #include "hex.h"
8 #include "setup.h"
9 #include "refs.h"
10 #include "object-store.h"
11 #include "commit.h"
12 #include "tree-walk.h"
13 #include "attr.h"
14 #include "archive.h"
15 #include "parse-options.h"
16 #include "unpack-trees.h"
17 #include "dir.h"
18 #include "quote.h"
20 static char const * const archive_usage[] = {
21 N_("git archive [<options>] <tree-ish> [<path>...]"),
22 "git archive --list",
23 N_("git archive --remote <repo> [--exec <cmd>] [<options>] <tree-ish> [<path>...]"),
24 N_("git archive --remote <repo> [--exec <cmd>] --list"),
25 NULL
28 static const struct archiver **archivers;
29 static int nr_archivers;
30 static int alloc_archivers;
31 static int remote_allow_unreachable;
33 void register_archiver(struct archiver *ar)
35 ALLOC_GROW(archivers, nr_archivers + 1, alloc_archivers);
36 archivers[nr_archivers++] = ar;
39 void init_archivers(void)
41 init_tar_archiver();
42 init_zip_archiver();
45 static void format_subst(const struct commit *commit,
46 const char *src, size_t len,
47 struct strbuf *buf, struct pretty_print_context *ctx)
49 char *to_free = NULL;
50 struct strbuf fmt = STRBUF_INIT;
52 if (src == buf->buf)
53 to_free = strbuf_detach(buf, NULL);
54 for (;;) {
55 const char *b, *c;
57 b = memmem(src, len, "$Format:", 8);
58 if (!b)
59 break;
60 c = memchr(b + 8, '$', (src + len) - b - 8);
61 if (!c)
62 break;
64 strbuf_reset(&fmt);
65 strbuf_add(&fmt, b + 8, c - b - 8);
67 strbuf_add(buf, src, b - src);
68 repo_format_commit_message(the_repository, commit, fmt.buf,
69 buf, ctx);
70 len -= c + 1 - src;
71 src = c + 1;
73 strbuf_add(buf, src, len);
74 strbuf_release(&fmt);
75 free(to_free);
78 static void *object_file_to_archive(const struct archiver_args *args,
79 const char *path,
80 const struct object_id *oid,
81 unsigned int mode,
82 enum object_type *type,
83 unsigned long *sizep)
85 void *buffer;
86 const struct commit *commit = args->convert ? args->commit : NULL;
87 struct checkout_metadata meta;
89 init_checkout_metadata(&meta, args->refname,
90 args->commit_oid ? args->commit_oid :
91 (args->tree ? &args->tree->object.oid : NULL), oid);
93 path += args->baselen;
94 buffer = repo_read_object_file(the_repository, oid, type, sizep);
95 if (buffer && S_ISREG(mode)) {
96 struct strbuf buf = STRBUF_INIT;
97 size_t size = 0;
99 strbuf_attach(&buf, buffer, *sizep, *sizep + 1);
100 convert_to_working_tree(args->repo->index, path, buf.buf, buf.len, &buf, &meta);
101 if (commit)
102 format_subst(commit, buf.buf, buf.len, &buf, args->pretty_ctx);
103 buffer = strbuf_detach(&buf, &size);
104 *sizep = size;
107 return buffer;
110 struct directory {
111 struct directory *up;
112 struct object_id oid;
113 int baselen, len;
114 unsigned mode;
115 char path[FLEX_ARRAY];
118 struct archiver_context {
119 struct archiver_args *args;
120 write_archive_entry_fn_t write_entry;
121 struct directory *bottom;
124 static const struct attr_check *get_archive_attrs(struct index_state *istate,
125 const char *path)
127 static struct attr_check *check;
128 if (!check)
129 check = attr_check_initl("export-ignore", "export-subst", NULL);
130 git_check_attr(istate, NULL, path, check);
131 return check;
134 static int check_attr_export_ignore(const struct attr_check *check)
136 return check && ATTR_TRUE(check->items[0].value);
139 static int check_attr_export_subst(const struct attr_check *check)
141 return check && ATTR_TRUE(check->items[1].value);
144 static int write_archive_entry(const struct object_id *oid, const char *base,
145 int baselen, const char *filename, unsigned mode,
146 void *context)
148 static struct strbuf path = STRBUF_INIT;
149 struct archiver_context *c = context;
150 struct archiver_args *args = c->args;
151 write_archive_entry_fn_t write_entry = c->write_entry;
152 int err;
153 const char *path_without_prefix;
154 unsigned long size;
155 void *buffer;
156 enum object_type type;
158 args->convert = 0;
159 strbuf_reset(&path);
160 strbuf_grow(&path, PATH_MAX);
161 strbuf_add(&path, args->base, args->baselen);
162 strbuf_add(&path, base, baselen);
163 strbuf_addstr(&path, filename);
164 if (S_ISDIR(mode) || S_ISGITLINK(mode))
165 strbuf_addch(&path, '/');
166 path_without_prefix = path.buf + args->baselen;
168 if (!S_ISDIR(mode)) {
169 const struct attr_check *check;
170 check = get_archive_attrs(args->repo->index, path_without_prefix);
171 if (check_attr_export_ignore(check))
172 return 0;
173 args->convert = check_attr_export_subst(check);
176 if (args->verbose)
177 fprintf(stderr, "%.*s\n", (int)path.len, path.buf);
179 if (S_ISDIR(mode) || S_ISGITLINK(mode)) {
180 err = write_entry(args, oid, path.buf, path.len, mode, NULL, 0);
181 if (err)
182 return err;
183 return (S_ISDIR(mode) ? READ_TREE_RECURSIVE : 0);
186 /* Stream it? */
187 if (S_ISREG(mode) && !args->convert &&
188 oid_object_info(args->repo, oid, &size) == OBJ_BLOB &&
189 size > big_file_threshold)
190 return write_entry(args, oid, path.buf, path.len, mode, NULL, size);
192 buffer = object_file_to_archive(args, path.buf, oid, mode, &type, &size);
193 if (!buffer)
194 return error(_("cannot read '%s'"), oid_to_hex(oid));
195 err = write_entry(args, oid, path.buf, path.len, mode, buffer, size);
196 free(buffer);
197 return err;
200 static void queue_directory(const struct object_id *oid,
201 struct strbuf *base, const char *filename,
202 unsigned mode, struct archiver_context *c)
204 struct directory *d;
205 size_t len = st_add4(base->len, 1, strlen(filename), 1);
206 d = xmalloc(st_add(sizeof(*d), len));
207 d->up = c->bottom;
208 d->baselen = base->len;
209 d->mode = mode;
210 c->bottom = d;
211 d->len = xsnprintf(d->path, len, "%.*s%s/", (int)base->len, base->buf, filename);
212 oidcpy(&d->oid, oid);
215 static int write_directory(struct archiver_context *c)
217 struct directory *d = c->bottom;
218 int ret;
220 if (!d)
221 return 0;
222 c->bottom = d->up;
223 d->path[d->len - 1] = '\0'; /* no trailing slash */
224 ret =
225 write_directory(c) ||
226 write_archive_entry(&d->oid, d->path, d->baselen,
227 d->path + d->baselen, d->mode,
228 c) != READ_TREE_RECURSIVE;
229 free(d);
230 return ret ? -1 : 0;
233 static int queue_or_write_archive_entry(const struct object_id *oid,
234 struct strbuf *base, const char *filename,
235 unsigned mode, void *context)
237 struct archiver_context *c = context;
239 while (c->bottom &&
240 !(base->len >= c->bottom->len &&
241 !strncmp(base->buf, c->bottom->path, c->bottom->len))) {
242 struct directory *next = c->bottom->up;
243 free(c->bottom);
244 c->bottom = next;
247 if (S_ISDIR(mode)) {
248 size_t baselen = base->len;
249 const struct attr_check *check;
251 /* Borrow base, but restore its original value when done. */
252 strbuf_addstr(base, filename);
253 strbuf_addch(base, '/');
254 check = get_archive_attrs(c->args->repo->index, base->buf);
255 strbuf_setlen(base, baselen);
257 if (check_attr_export_ignore(check))
258 return 0;
259 queue_directory(oid, base, filename, mode, c);
260 return READ_TREE_RECURSIVE;
263 if (write_directory(c))
264 return -1;
265 return write_archive_entry(oid, base->buf, base->len, filename, mode,
266 context);
269 struct extra_file_info {
270 char *base;
271 struct stat stat;
272 void *content;
275 int write_archive_entries(struct archiver_args *args,
276 write_archive_entry_fn_t write_entry)
278 struct archiver_context context;
279 struct unpack_trees_options opts;
280 struct tree_desc t;
281 int err;
282 struct strbuf path_in_archive = STRBUF_INIT;
283 struct strbuf content = STRBUF_INIT;
284 struct object_id fake_oid;
285 int i;
287 oidcpy(&fake_oid, null_oid());
289 if (args->baselen > 0 && args->base[args->baselen - 1] == '/') {
290 size_t len = args->baselen;
292 while (len > 1 && args->base[len - 2] == '/')
293 len--;
294 if (args->verbose)
295 fprintf(stderr, "%.*s\n", (int)len, args->base);
296 err = write_entry(args, &args->tree->object.oid, args->base,
297 len, 040777, NULL, 0);
298 if (err)
299 return err;
302 memset(&context, 0, sizeof(context));
303 context.args = args;
304 context.write_entry = write_entry;
307 * Setup index and instruct attr to read index only
309 if (!args->worktree_attributes) {
310 memset(&opts, 0, sizeof(opts));
311 opts.index_only = 1;
312 opts.head_idx = -1;
313 opts.src_index = args->repo->index;
314 opts.dst_index = args->repo->index;
315 opts.fn = oneway_merge;
316 init_tree_desc(&t, args->tree->buffer, args->tree->size);
317 if (unpack_trees(1, &t, &opts))
318 return -1;
319 git_attr_set_direction(GIT_ATTR_INDEX);
322 err = read_tree(args->repo, args->tree,
323 &args->pathspec,
324 queue_or_write_archive_entry,
325 &context);
326 if (err == READ_TREE_RECURSIVE)
327 err = 0;
328 while (context.bottom) {
329 struct directory *next = context.bottom->up;
330 free(context.bottom);
331 context.bottom = next;
334 for (i = 0; i < args->extra_files.nr; i++) {
335 struct string_list_item *item = args->extra_files.items + i;
336 char *path = item->string;
337 struct extra_file_info *info = item->util;
339 put_be64(fake_oid.hash, i + 1);
341 if (!info->content) {
342 strbuf_reset(&path_in_archive);
343 if (info->base)
344 strbuf_addstr(&path_in_archive, info->base);
345 strbuf_addstr(&path_in_archive, basename(path));
347 strbuf_reset(&content);
348 if (strbuf_read_file(&content, path, info->stat.st_size) < 0)
349 err = error_errno(_("cannot read '%s'"), path);
350 else
351 err = write_entry(args, &fake_oid, path_in_archive.buf,
352 path_in_archive.len,
353 canon_mode(info->stat.st_mode),
354 content.buf, content.len);
355 } else {
356 err = write_entry(args, &fake_oid,
357 path, strlen(path),
358 canon_mode(info->stat.st_mode),
359 info->content, info->stat.st_size);
362 if (err)
363 break;
365 strbuf_release(&path_in_archive);
366 strbuf_release(&content);
368 return err;
371 static const struct archiver *lookup_archiver(const char *name)
373 int i;
375 if (!name)
376 return NULL;
378 for (i = 0; i < nr_archivers; i++) {
379 if (!strcmp(name, archivers[i]->name))
380 return archivers[i];
382 return NULL;
385 struct path_exists_context {
386 struct pathspec pathspec;
387 struct archiver_args *args;
390 static int reject_entry(const struct object_id *oid UNUSED,
391 struct strbuf *base,
392 const char *filename, unsigned mode,
393 void *context)
395 int ret = -1;
396 struct path_exists_context *ctx = context;
398 if (S_ISDIR(mode)) {
399 struct strbuf sb = STRBUF_INIT;
400 strbuf_addbuf(&sb, base);
401 strbuf_addstr(&sb, filename);
402 if (!match_pathspec(ctx->args->repo->index,
403 &ctx->pathspec,
404 sb.buf, sb.len, 0, NULL, 1))
405 ret = READ_TREE_RECURSIVE;
406 strbuf_release(&sb);
408 return ret;
411 static int path_exists(struct archiver_args *args, const char *path)
413 const char *paths[] = { path, NULL };
414 struct path_exists_context ctx;
415 int ret;
417 ctx.args = args;
418 parse_pathspec(&ctx.pathspec, 0, 0, "", paths);
419 ctx.pathspec.recursive = 1;
420 ret = read_tree(args->repo, args->tree,
421 &ctx.pathspec,
422 reject_entry, &ctx);
423 clear_pathspec(&ctx.pathspec);
424 return ret != 0;
427 static void parse_pathspec_arg(const char **pathspec,
428 struct archiver_args *ar_args)
431 * must be consistent with parse_pathspec in path_exists()
432 * Also if pathspec patterns are dependent, we're in big
433 * trouble as we test each one separately
435 parse_pathspec(&ar_args->pathspec, 0,
436 PATHSPEC_PREFER_FULL,
437 "", pathspec);
438 ar_args->pathspec.recursive = 1;
439 if (pathspec) {
440 while (*pathspec) {
441 if (**pathspec && !path_exists(ar_args, *pathspec))
442 die(_("pathspec '%s' did not match any files"), *pathspec);
443 pathspec++;
448 static void parse_treeish_arg(const char **argv,
449 struct archiver_args *ar_args, const char *prefix,
450 int remote)
452 const char *name = argv[0];
453 const struct object_id *commit_oid;
454 time_t archive_time;
455 struct tree *tree;
456 const struct commit *commit;
457 struct object_id oid;
458 char *ref = NULL;
460 /* Remotes are only allowed to fetch actual refs */
461 if (remote && !remote_allow_unreachable) {
462 const char *colon = strchrnul(name, ':');
463 int refnamelen = colon - name;
465 if (!repo_dwim_ref(the_repository, name, refnamelen, &oid, &ref, 0))
466 die(_("no such ref: %.*s"), refnamelen, name);
467 } else {
468 repo_dwim_ref(the_repository, name, strlen(name), &oid, &ref,
472 if (repo_get_oid(the_repository, name, &oid))
473 die(_("not a valid object name: %s"), name);
475 commit = lookup_commit_reference_gently(ar_args->repo, &oid, 1);
476 if (commit) {
477 commit_oid = &commit->object.oid;
478 archive_time = commit->date;
479 } else {
480 commit_oid = NULL;
481 archive_time = time(NULL);
483 if (ar_args->mtime_option)
484 archive_time = approxidate(ar_args->mtime_option);
486 tree = parse_tree_indirect(&oid);
487 if (!tree)
488 die(_("not a tree object: %s"), oid_to_hex(&oid));
490 if (prefix) {
491 struct object_id tree_oid;
492 unsigned short mode;
493 int err;
495 err = get_tree_entry(ar_args->repo,
496 &tree->object.oid,
497 prefix, &tree_oid,
498 &mode);
499 if (err || !S_ISDIR(mode))
500 die(_("current working directory is untracked"));
502 tree = parse_tree_indirect(&tree_oid);
504 ar_args->refname = ref;
505 ar_args->tree = tree;
506 ar_args->commit_oid = commit_oid;
507 ar_args->commit = commit;
508 ar_args->time = archive_time;
511 static void extra_file_info_clear(void *util, const char *str UNUSED)
513 struct extra_file_info *info = util;
514 free(info->base);
515 free(info->content);
516 free(info);
519 static int add_file_cb(const struct option *opt, const char *arg, int unset)
521 struct archiver_args *args = opt->value;
522 const char **basep = (const char **)opt->defval;
523 const char *base = *basep;
524 char *path;
525 struct string_list_item *item;
526 struct extra_file_info *info;
528 if (unset) {
529 string_list_clear_func(&args->extra_files,
530 extra_file_info_clear);
531 return 0;
534 if (!arg)
535 return -1;
537 info = xmalloc(sizeof(*info));
538 info->base = xstrdup_or_null(base);
540 if (!strcmp(opt->long_name, "add-file")) {
541 path = prefix_filename(args->prefix, arg);
542 if (stat(path, &info->stat))
543 die(_("File not found: %s"), path);
544 if (!S_ISREG(info->stat.st_mode))
545 die(_("Not a regular file: %s"), path);
546 info->content = NULL; /* read the file later */
547 } else if (!strcmp(opt->long_name, "add-virtual-file")) {
548 struct strbuf buf = STRBUF_INIT;
549 const char *p = arg;
551 if (*p != '"')
552 p = strchr(p, ':');
553 else if (unquote_c_style(&buf, p, &p) < 0)
554 die(_("unclosed quote: '%s'"), arg);
556 if (!p || *p != ':')
557 die(_("missing colon: '%s'"), arg);
559 if (p == arg)
560 die(_("empty file name: '%s'"), arg);
562 path = buf.len ?
563 strbuf_detach(&buf, NULL) : xstrndup(arg, p - arg);
565 if (args->prefix) {
566 char *save = path;
567 path = prefix_filename(args->prefix, path);
568 free(save);
570 memset(&info->stat, 0, sizeof(info->stat));
571 info->stat.st_mode = S_IFREG | 0644;
572 info->content = xstrdup(p + 1);
573 info->stat.st_size = strlen(info->content);
574 } else {
575 BUG("add_file_cb() called for %s", opt->long_name);
577 item = string_list_append_nodup(&args->extra_files, path);
578 item->util = info;
580 return 0;
583 static int number_callback(const struct option *opt, const char *arg, int unset)
585 BUG_ON_OPT_NEG(unset);
586 *(int *)opt->value = strtol(arg, NULL, 10);
587 return 0;
590 static int parse_archive_args(int argc, const char **argv,
591 const struct archiver **ar, struct archiver_args *args,
592 const char *name_hint, int is_remote)
594 const char *format = NULL;
595 const char *base = NULL;
596 const char *remote = NULL;
597 const char *exec = NULL;
598 const char *output = NULL;
599 const char *mtime_option = NULL;
600 int compression_level = -1;
601 int verbose = 0;
602 int i;
603 int list = 0;
604 int worktree_attributes = 0;
605 struct option opts[] = {
606 OPT_GROUP(""),
607 OPT_STRING(0, "format", &format, N_("fmt"), N_("archive format")),
608 OPT_STRING(0, "prefix", &base, N_("prefix"),
609 N_("prepend prefix to each pathname in the archive")),
610 { OPTION_CALLBACK, 0, "add-file", args, N_("file"),
611 N_("add untracked file to archive"), 0, add_file_cb,
612 (intptr_t)&base },
613 { OPTION_CALLBACK, 0, "add-virtual-file", args,
614 N_("path:content"), N_("add untracked file to archive"), 0,
615 add_file_cb, (intptr_t)&base },
616 OPT_STRING('o', "output", &output, N_("file"),
617 N_("write the archive to this file")),
618 OPT_BOOL(0, "worktree-attributes", &worktree_attributes,
619 N_("read .gitattributes in working directory")),
620 OPT__VERBOSE(&verbose, N_("report archived files on stderr")),
621 { OPTION_STRING, 0, "mtime", &mtime_option, N_("time"),
622 N_("set modification time of archive entries"),
623 PARSE_OPT_NONEG },
624 OPT_NUMBER_CALLBACK(&compression_level,
625 N_("set compression level"), number_callback),
626 OPT_GROUP(""),
627 OPT_BOOL('l', "list", &list,
628 N_("list supported archive formats")),
629 OPT_GROUP(""),
630 OPT_STRING(0, "remote", &remote, N_("repo"),
631 N_("retrieve the archive from remote repository <repo>")),
632 OPT_STRING(0, "exec", &exec, N_("command"),
633 N_("path to the remote git-upload-archive command")),
634 OPT_END()
637 argc = parse_options(argc, argv, NULL, opts, archive_usage, 0);
639 if (remote)
640 die(_("Unexpected option --remote"));
641 if (exec)
642 die(_("the option '%s' requires '%s'"), "--exec", "--remote");
643 if (output)
644 die(_("Unexpected option --output"));
645 if (is_remote && args->extra_files.nr)
646 die(_("options '%s' and '%s' cannot be used together"), "--add-file", "--remote");
648 if (!base)
649 base = "";
651 if (list) {
652 for (i = 0; i < nr_archivers; i++)
653 if (!is_remote || archivers[i]->flags & ARCHIVER_REMOTE)
654 printf("%s\n", archivers[i]->name);
655 exit(0);
658 if (!format && name_hint)
659 format = archive_format_from_filename(name_hint);
660 if (!format)
661 format = "tar";
663 /* We need at least one parameter -- tree-ish */
664 if (argc < 1)
665 usage_with_options(archive_usage, opts);
666 *ar = lookup_archiver(format);
667 if (!*ar || (is_remote && !((*ar)->flags & ARCHIVER_REMOTE)))
668 die(_("Unknown archive format '%s'"), format);
670 args->compression_level = Z_DEFAULT_COMPRESSION;
671 if (compression_level != -1) {
672 int levels_ok = (*ar)->flags & ARCHIVER_WANT_COMPRESSION_LEVELS;
673 int high_ok = (*ar)->flags & ARCHIVER_HIGH_COMPRESSION_LEVELS;
674 if (levels_ok && (compression_level <= 9 || high_ok))
675 args->compression_level = compression_level;
676 else {
677 die(_("Argument not supported for format '%s': -%d"),
678 format, compression_level);
681 args->verbose = verbose;
682 args->base = base;
683 args->baselen = strlen(base);
684 args->worktree_attributes = worktree_attributes;
685 args->mtime_option = mtime_option;
687 return argc;
690 int write_archive(int argc, const char **argv, const char *prefix,
691 struct repository *repo,
692 const char *name_hint, int remote)
694 const struct archiver *ar = NULL;
695 struct pretty_print_describe_status describe_status = {0};
696 struct pretty_print_context ctx = {0};
697 struct archiver_args args;
698 int rc;
700 git_config_get_bool("uploadarchive.allowunreachable", &remote_allow_unreachable);
701 git_config(git_default_config, NULL);
703 describe_status.max_invocations = 1;
704 ctx.date_mode.type = DATE_NORMAL;
705 ctx.abbrev = DEFAULT_ABBREV;
706 ctx.describe_status = &describe_status;
707 args.pretty_ctx = &ctx;
708 args.repo = repo;
709 args.prefix = prefix;
710 string_list_init_dup(&args.extra_files);
711 argc = parse_archive_args(argc, argv, &ar, &args, name_hint, remote);
712 if (!startup_info->have_repository) {
714 * We know this will die() with an error, so we could just
715 * die ourselves; but its error message will be more specific
716 * than what we could write here.
718 setup_git_directory();
721 parse_treeish_arg(argv, &args, prefix, remote);
722 parse_pathspec_arg(argv + 1, &args);
724 rc = ar->write_archive(ar, &args);
726 string_list_clear_func(&args.extra_files, extra_file_info_clear);
727 free(args.refname);
728 clear_pathspec(&args.pathspec);
730 return rc;
733 static int match_extension(const char *filename, const char *ext)
735 int prefixlen = strlen(filename) - strlen(ext);
738 * We need 1 character for the '.', and 1 character to ensure that the
739 * prefix is non-empty (k.e., we don't match .tar.gz with no actual
740 * filename).
742 if (prefixlen < 2 || filename[prefixlen - 1] != '.')
743 return 0;
744 return !strcmp(filename + prefixlen, ext);
747 const char *archive_format_from_filename(const char *filename)
749 int i;
751 for (i = 0; i < nr_archivers; i++)
752 if (match_extension(filename, archivers[i]->name))
753 return archivers[i]->name;
754 return NULL;