archive: support filtering paths with glob
[git] / archive.c
1 #include "cache.h"
2 #include "commit.h"
3 #include "tree-walk.h"
4 #include "attr.h"
5 #include "archive.h"
6 #include "parse-options.h"
7 #include "unpack-trees.h"
8 #include "dir.h"
9
10 static char const * const archive_usage[] = {
11         N_("git archive [options] <tree-ish> [<path>...]"),
12         N_("git archive --list"),
13         N_("git archive --remote <repo> [--exec <cmd>] [options] <tree-ish> [<path>...]"),
14         N_("git archive --remote <repo> [--exec <cmd>] --list"),
15         NULL
16 };
17
18 static const struct archiver **archivers;
19 static int nr_archivers;
20 static int alloc_archivers;
21
22 void register_archiver(struct archiver *ar)
23 {
24         ALLOC_GROW(archivers, nr_archivers + 1, alloc_archivers);
25         archivers[nr_archivers++] = ar;
26 }
27
28 static void format_subst(const struct commit *commit,
29                          const char *src, size_t len,
30                          struct strbuf *buf)
31 {
32         char *to_free = NULL;
33         struct strbuf fmt = STRBUF_INIT;
34         struct pretty_print_context ctx = {0};
35         ctx.date_mode = DATE_NORMAL;
36         ctx.abbrev = DEFAULT_ABBREV;
37
38         if (src == buf->buf)
39                 to_free = strbuf_detach(buf, NULL);
40         for (;;) {
41                 const char *b, *c;
42
43                 b = memmem(src, len, "$Format:", 8);
44                 if (!b)
45                         break;
46                 c = memchr(b + 8, '$', (src + len) - b - 8);
47                 if (!c)
48                         break;
49
50                 strbuf_reset(&fmt);
51                 strbuf_add(&fmt, b + 8, c - b - 8);
52
53                 strbuf_add(buf, src, b - src);
54                 format_commit_message(commit, fmt.buf, buf, &ctx);
55                 len -= c + 1 - src;
56                 src  = c + 1;
57         }
58         strbuf_add(buf, src, len);
59         strbuf_release(&fmt);
60         free(to_free);
61 }
62
63 void *sha1_file_to_archive(const struct archiver_args *args,
64                            const char *path, const unsigned char *sha1,
65                            unsigned int mode, enum object_type *type,
66                            unsigned long *sizep)
67 {
68         void *buffer;
69         const struct commit *commit = args->convert ? args->commit : NULL;
70
71         path += args->baselen;
72         buffer = read_sha1_file(sha1, type, sizep);
73         if (buffer && S_ISREG(mode)) {
74                 struct strbuf buf = STRBUF_INIT;
75                 size_t size = 0;
76
77                 strbuf_attach(&buf, buffer, *sizep, *sizep + 1);
78                 convert_to_working_tree(path, buf.buf, buf.len, &buf);
79                 if (commit)
80                         format_subst(commit, buf.buf, buf.len, &buf);
81                 buffer = strbuf_detach(&buf, &size);
82                 *sizep = size;
83         }
84
85         return buffer;
86 }
87
88 static void setup_archive_check(struct git_attr_check *check)
89 {
90         static struct git_attr *attr_export_ignore;
91         static struct git_attr *attr_export_subst;
92
93         if (!attr_export_ignore) {
94                 attr_export_ignore = git_attr("export-ignore");
95                 attr_export_subst = git_attr("export-subst");
96         }
97         check[0].attr = attr_export_ignore;
98         check[1].attr = attr_export_subst;
99 }
100
101 struct directory {
102         struct directory *up;
103         unsigned char sha1[20];
104         int baselen, len;
105         unsigned mode;
106         int stage;
107         char path[FLEX_ARRAY];
108 };
109
110 struct archiver_context {
111         struct archiver_args *args;
112         write_archive_entry_fn_t write_entry;
113         struct directory *bottom;
114 };
115
116 static int write_archive_entry(const unsigned char *sha1, const char *base,
117                 int baselen, const char *filename, unsigned mode, int stage,
118                 void *context)
119 {
120         static struct strbuf path = STRBUF_INIT;
121         struct archiver_context *c = context;
122         struct archiver_args *args = c->args;
123         write_archive_entry_fn_t write_entry = c->write_entry;
124         struct git_attr_check check[2];
125         const char *path_without_prefix;
126         int err;
127
128         args->convert = 0;
129         strbuf_reset(&path);
130         strbuf_grow(&path, PATH_MAX);
131         strbuf_add(&path, args->base, args->baselen);
132         strbuf_add(&path, base, baselen);
133         strbuf_addstr(&path, filename);
134         if (S_ISDIR(mode) || S_ISGITLINK(mode))
135                 strbuf_addch(&path, '/');
136         path_without_prefix = path.buf + args->baselen;
137
138         setup_archive_check(check);
139         if (!git_check_attr(path_without_prefix, ARRAY_SIZE(check), check)) {
140                 if (ATTR_TRUE(check[0].value))
141                         return 0;
142                 args->convert = ATTR_TRUE(check[1].value);
143         }
144
145         if (S_ISDIR(mode) || S_ISGITLINK(mode)) {
146                 if (args->verbose)
147                         fprintf(stderr, "%.*s\n", (int)path.len, path.buf);
148                 err = write_entry(args, sha1, path.buf, path.len, mode);
149                 if (err)
150                         return err;
151                 return (S_ISDIR(mode) ? READ_TREE_RECURSIVE : 0);
152         }
153
154         if (args->verbose)
155                 fprintf(stderr, "%.*s\n", (int)path.len, path.buf);
156         return write_entry(args, sha1, path.buf, path.len, mode);
157 }
158
159 static void queue_directory(const unsigned char *sha1,
160                 const char *base, int baselen, const char *filename,
161                 unsigned mode, int stage, struct archiver_context *c)
162 {
163         struct directory *d;
164         d = xmallocz(sizeof(*d) + baselen + 1 + strlen(filename));
165         d->up      = c->bottom;
166         d->baselen = baselen;
167         d->mode    = mode;
168         d->stage   = stage;
169         c->bottom  = d;
170         d->len = sprintf(d->path, "%.*s%s/", baselen, base, filename);
171         hashcpy(d->sha1, sha1);
172 }
173
174 static int write_directory(struct archiver_context *c)
175 {
176         struct directory *d = c->bottom;
177         int ret;
178
179         if (!d)
180                 return 0;
181         c->bottom = d->up;
182         d->path[d->len - 1] = '\0'; /* no trailing slash */
183         ret =
184                 write_directory(c) ||
185                 write_archive_entry(d->sha1, d->path, d->baselen,
186                                     d->path + d->baselen, d->mode,
187                                     d->stage, c) != READ_TREE_RECURSIVE;
188         free(d);
189         return ret ? -1 : 0;
190 }
191
192 static int queue_or_write_archive_entry(const unsigned char *sha1,
193                 const char *base, int baselen, const char *filename,
194                 unsigned mode, int stage, void *context)
195 {
196         struct archiver_context *c = context;
197
198         while (c->bottom &&
199                !(baselen >= c->bottom->len &&
200                  !strncmp(base, c->bottom->path, c->bottom->len))) {
201                 struct directory *next = c->bottom->up;
202                 free(c->bottom);
203                 c->bottom = next;
204         }
205
206         if (S_ISDIR(mode)) {
207                 queue_directory(sha1, base, baselen, filename,
208                                 mode, stage, c);
209                 return READ_TREE_RECURSIVE;
210         }
211
212         if (write_directory(c))
213                 return -1;
214         return write_archive_entry(sha1, base, baselen, filename, mode,
215                                    stage, context);
216 }
217
218 int write_archive_entries(struct archiver_args *args,
219                 write_archive_entry_fn_t write_entry)
220 {
221         struct archiver_context context;
222         struct unpack_trees_options opts;
223         struct tree_desc t;
224         int err;
225
226         if (args->baselen > 0 && args->base[args->baselen - 1] == '/') {
227                 size_t len = args->baselen;
228
229                 while (len > 1 && args->base[len - 2] == '/')
230                         len--;
231                 if (args->verbose)
232                         fprintf(stderr, "%.*s\n", (int)len, args->base);
233                 err = write_entry(args, args->tree->object.sha1, args->base,
234                                   len, 040777);
235                 if (err)
236                         return err;
237         }
238
239         memset(&context, 0, sizeof(context));
240         context.args = args;
241         context.write_entry = write_entry;
242
243         /*
244          * Setup index and instruct attr to read index only
245          */
246         if (!args->worktree_attributes) {
247                 memset(&opts, 0, sizeof(opts));
248                 opts.index_only = 1;
249                 opts.head_idx = -1;
250                 opts.src_index = &the_index;
251                 opts.dst_index = &the_index;
252                 opts.fn = oneway_merge;
253                 init_tree_desc(&t, args->tree->buffer, args->tree->size);
254                 if (unpack_trees(1, &t, &opts))
255                         return -1;
256                 git_attr_set_direction(GIT_ATTR_INDEX, &the_index);
257         }
258
259         err = read_tree_recursive(args->tree, "", 0, 0, &args->pathspec,
260                                   args->pathspec.has_wildcard ?
261                                   queue_or_write_archive_entry :
262                                   write_archive_entry,
263                                   &context);
264         if (err == READ_TREE_RECURSIVE)
265                 err = 0;
266         while (context.bottom) {
267                 struct directory *next = context.bottom->up;
268                 free(context.bottom);
269                 context.bottom = next;
270         }
271         return err;
272 }
273
274 static const struct archiver *lookup_archiver(const char *name)
275 {
276         int i;
277
278         if (!name)
279                 return NULL;
280
281         for (i = 0; i < nr_archivers; i++) {
282                 if (!strcmp(name, archivers[i]->name))
283                         return archivers[i];
284         }
285         return NULL;
286 }
287
288 static int reject_entry(const unsigned char *sha1, const char *base,
289                         int baselen, const char *filename, unsigned mode,
290                         int stage, void *context)
291 {
292         int ret = -1;
293         if (S_ISDIR(mode)) {
294                 struct strbuf sb = STRBUF_INIT;
295                 strbuf_addstr(&sb, base);
296                 strbuf_addstr(&sb, filename);
297                 if (!match_pathspec(context, sb.buf, sb.len, 0, NULL, 1))
298                         ret = READ_TREE_RECURSIVE;
299                 strbuf_release(&sb);
300         }
301         return ret;
302 }
303
304 static int path_exists(struct tree *tree, const char *path)
305 {
306         const char *paths[] = { path, NULL };
307         struct pathspec pathspec;
308         int ret;
309
310         parse_pathspec(&pathspec, 0, 0, "", paths);
311         pathspec.recursive = 1;
312         ret = read_tree_recursive(tree, "", 0, 0, &pathspec,
313                                   reject_entry, &pathspec);
314         free_pathspec(&pathspec);
315         return ret != 0;
316 }
317
318 static void parse_pathspec_arg(const char **pathspec,
319                 struct archiver_args *ar_args)
320 {
321         /*
322          * must be consistent with parse_pathspec in path_exists()
323          * Also if pathspec patterns are dependent, we're in big
324          * trouble as we test each one separately
325          */
326         parse_pathspec(&ar_args->pathspec, 0,
327                        PATHSPEC_PREFER_FULL,
328                        "", pathspec);
329         ar_args->pathspec.recursive = 1;
330         if (pathspec) {
331                 while (*pathspec) {
332                         if (**pathspec && !path_exists(ar_args->tree, *pathspec))
333                                 die(_("pathspec '%s' did not match any files"), *pathspec);
334                         pathspec++;
335                 }
336         }
337 }
338
339 static void parse_treeish_arg(const char **argv,
340                 struct archiver_args *ar_args, const char *prefix,
341                 int remote)
342 {
343         const char *name = argv[0];
344         const unsigned char *commit_sha1;
345         time_t archive_time;
346         struct tree *tree;
347         const struct commit *commit;
348         unsigned char sha1[20];
349
350         /* Remotes are only allowed to fetch actual refs */
351         if (remote) {
352                 char *ref = NULL;
353                 const char *colon = strchr(name, ':');
354                 int refnamelen = colon ? colon - name : strlen(name);
355
356                 if (!dwim_ref(name, refnamelen, sha1, &ref))
357                         die("no such ref: %.*s", refnamelen, name);
358                 free(ref);
359         }
360
361         if (get_sha1(name, sha1))
362                 die("Not a valid object name");
363
364         commit = lookup_commit_reference_gently(sha1, 1);
365         if (commit) {
366                 commit_sha1 = commit->object.sha1;
367                 archive_time = commit->date;
368         } else {
369                 commit_sha1 = NULL;
370                 archive_time = time(NULL);
371         }
372
373         tree = parse_tree_indirect(sha1);
374         if (tree == NULL)
375                 die("not a tree object");
376
377         if (prefix) {
378                 unsigned char tree_sha1[20];
379                 unsigned int mode;
380                 int err;
381
382                 err = get_tree_entry(tree->object.sha1, prefix,
383                                      tree_sha1, &mode);
384                 if (err || !S_ISDIR(mode))
385                         die("current working directory is untracked");
386
387                 tree = parse_tree_indirect(tree_sha1);
388         }
389         ar_args->tree = tree;
390         ar_args->commit_sha1 = commit_sha1;
391         ar_args->commit = commit;
392         ar_args->time = archive_time;
393 }
394
395 #define OPT__COMPR(s, v, h, p) \
396         { OPTION_SET_INT, (s), NULL, (v), NULL, (h), \
397           PARSE_OPT_NOARG | PARSE_OPT_NONEG, NULL, (p) }
398 #define OPT__COMPR_HIDDEN(s, v, p) \
399         { OPTION_SET_INT, (s), NULL, (v), NULL, "", \
400           PARSE_OPT_NOARG | PARSE_OPT_NONEG | PARSE_OPT_HIDDEN, NULL, (p) }
401
402 static int parse_archive_args(int argc, const char **argv,
403                 const struct archiver **ar, struct archiver_args *args,
404                 const char *name_hint, int is_remote)
405 {
406         const char *format = NULL;
407         const char *base = NULL;
408         const char *remote = NULL;
409         const char *exec = NULL;
410         const char *output = NULL;
411         int compression_level = -1;
412         int verbose = 0;
413         int i;
414         int list = 0;
415         int worktree_attributes = 0;
416         struct option opts[] = {
417                 OPT_GROUP(""),
418                 OPT_STRING(0, "format", &format, N_("fmt"), N_("archive format")),
419                 OPT_STRING(0, "prefix", &base, N_("prefix"),
420                         N_("prepend prefix to each pathname in the archive")),
421                 OPT_STRING('o', "output", &output, N_("file"),
422                         N_("write the archive to this file")),
423                 OPT_BOOL(0, "worktree-attributes", &worktree_attributes,
424                         N_("read .gitattributes in working directory")),
425                 OPT__VERBOSE(&verbose, N_("report archived files on stderr")),
426                 OPT__COMPR('0', &compression_level, N_("store only"), 0),
427                 OPT__COMPR('1', &compression_level, N_("compress faster"), 1),
428                 OPT__COMPR_HIDDEN('2', &compression_level, 2),
429                 OPT__COMPR_HIDDEN('3', &compression_level, 3),
430                 OPT__COMPR_HIDDEN('4', &compression_level, 4),
431                 OPT__COMPR_HIDDEN('5', &compression_level, 5),
432                 OPT__COMPR_HIDDEN('6', &compression_level, 6),
433                 OPT__COMPR_HIDDEN('7', &compression_level, 7),
434                 OPT__COMPR_HIDDEN('8', &compression_level, 8),
435                 OPT__COMPR('9', &compression_level, N_("compress better"), 9),
436                 OPT_GROUP(""),
437                 OPT_BOOL('l', "list", &list,
438                         N_("list supported archive formats")),
439                 OPT_GROUP(""),
440                 OPT_STRING(0, "remote", &remote, N_("repo"),
441                         N_("retrieve the archive from remote repository <repo>")),
442                 OPT_STRING(0, "exec", &exec, N_("command"),
443                         N_("path to the remote git-upload-archive command")),
444                 OPT_END()
445         };
446
447         argc = parse_options(argc, argv, NULL, opts, archive_usage, 0);
448
449         if (remote)
450                 die("Unexpected option --remote");
451         if (exec)
452                 die("Option --exec can only be used together with --remote");
453         if (output)
454                 die("Unexpected option --output");
455
456         if (!base)
457                 base = "";
458
459         if (list) {
460                 for (i = 0; i < nr_archivers; i++)
461                         if (!is_remote || archivers[i]->flags & ARCHIVER_REMOTE)
462                                 printf("%s\n", archivers[i]->name);
463                 exit(0);
464         }
465
466         if (!format && name_hint)
467                 format = archive_format_from_filename(name_hint);
468         if (!format)
469                 format = "tar";
470
471         /* We need at least one parameter -- tree-ish */
472         if (argc < 1)
473                 usage_with_options(archive_usage, opts);
474         *ar = lookup_archiver(format);
475         if (!*ar || (is_remote && !((*ar)->flags & ARCHIVER_REMOTE)))
476                 die("Unknown archive format '%s'", format);
477
478         args->compression_level = Z_DEFAULT_COMPRESSION;
479         if (compression_level != -1) {
480                 if ((*ar)->flags & ARCHIVER_WANT_COMPRESSION_LEVELS)
481                         args->compression_level = compression_level;
482                 else {
483                         die("Argument not supported for format '%s': -%d",
484                                         format, compression_level);
485                 }
486         }
487         args->verbose = verbose;
488         args->base = base;
489         args->baselen = strlen(base);
490         args->worktree_attributes = worktree_attributes;
491
492         return argc;
493 }
494
495 int write_archive(int argc, const char **argv, const char *prefix,
496                   int setup_prefix, const char *name_hint, int remote)
497 {
498         int nongit = 0;
499         const struct archiver *ar = NULL;
500         struct archiver_args args;
501
502         if (setup_prefix && prefix == NULL)
503                 prefix = setup_git_directory_gently(&nongit);
504
505         git_config(git_default_config, NULL);
506         init_tar_archiver();
507         init_zip_archiver();
508
509         argc = parse_archive_args(argc, argv, &ar, &args, name_hint, remote);
510         if (nongit) {
511                 /*
512                  * We know this will die() with an error, so we could just
513                  * die ourselves; but its error message will be more specific
514                  * than what we could write here.
515                  */
516                 setup_git_directory();
517         }
518
519         parse_treeish_arg(argv, &args, prefix, remote);
520         parse_pathspec_arg(argv + 1, &args);
521
522         return ar->write_archive(ar, &args);
523 }
524
525 static int match_extension(const char *filename, const char *ext)
526 {
527         int prefixlen = strlen(filename) - strlen(ext);
528
529         /*
530          * We need 1 character for the '.', and 1 character to ensure that the
531          * prefix is non-empty (k.e., we don't match .tar.gz with no actual
532          * filename).
533          */
534         if (prefixlen < 2 || filename[prefixlen - 1] != '.')
535                 return 0;
536         return !strcmp(filename + prefixlen, ext);
537 }
538
539 const char *archive_format_from_filename(const char *filename)
540 {
541         int i;
542
543         for (i = 0; i < nr_archivers; i++)
544                 if (match_extension(filename, archivers[i]->name))
545                         return archivers[i]->name;
546         return NULL;
547 }