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