unpack-trees: add a new update_sparsity() function
[git] / builtin / sparse-checkout.c
1 #include "builtin.h"
2 #include "config.h"
3 #include "dir.h"
4 #include "parse-options.h"
5 #include "pathspec.h"
6 #include "repository.h"
7 #include "run-command.h"
8 #include "strbuf.h"
9 #include "string-list.h"
10 #include "cache.h"
11 #include "cache-tree.h"
12 #include "lockfile.h"
13 #include "resolve-undo.h"
14 #include "unpack-trees.h"
15 #include "wt-status.h"
16 #include "quote.h"
17
18 static const char *empty_base = "";
19
20 static char const * const builtin_sparse_checkout_usage[] = {
21         N_("git sparse-checkout (init|list|set|add|disable) <options>"),
22         NULL
23 };
24
25 static char *get_sparse_checkout_filename(void)
26 {
27         return git_pathdup("info/sparse-checkout");
28 }
29
30 static void write_patterns_to_file(FILE *fp, struct pattern_list *pl)
31 {
32         int i;
33
34         for (i = 0; i < pl->nr; i++) {
35                 struct path_pattern *p = pl->patterns[i];
36
37                 if (p->flags & PATTERN_FLAG_NEGATIVE)
38                         fprintf(fp, "!");
39
40                 fprintf(fp, "%s", p->pattern);
41
42                 if (p->flags & PATTERN_FLAG_MUSTBEDIR)
43                         fprintf(fp, "/");
44
45                 fprintf(fp, "\n");
46         }
47 }
48
49 static int sparse_checkout_list(int argc, const char **argv)
50 {
51         struct pattern_list pl;
52         char *sparse_filename;
53         int res;
54
55         memset(&pl, 0, sizeof(pl));
56
57         pl.use_cone_patterns = core_sparse_checkout_cone;
58
59         sparse_filename = get_sparse_checkout_filename();
60         res = add_patterns_from_file_to_list(sparse_filename, "", 0, &pl, NULL);
61         free(sparse_filename);
62
63         if (res < 0) {
64                 warning(_("this worktree is not sparse (sparse-checkout file may not exist)"));
65                 return 0;
66         }
67
68         if (pl.use_cone_patterns) {
69                 int i;
70                 struct pattern_entry *pe;
71                 struct hashmap_iter iter;
72                 struct string_list sl = STRING_LIST_INIT_DUP;
73
74                 hashmap_for_each_entry(&pl.recursive_hashmap, &iter, pe, ent) {
75                         /* pe->pattern starts with "/", skip it */
76                         string_list_insert(&sl, pe->pattern + 1);
77                 }
78
79                 string_list_sort(&sl);
80
81                 for (i = 0; i < sl.nr; i++) {
82                         quote_c_style(sl.items[i].string, NULL, stdout, 0);
83                         printf("\n");
84                 }
85
86                 return 0;
87         }
88
89         write_patterns_to_file(stdout, &pl);
90         clear_pattern_list(&pl);
91
92         return 0;
93 }
94
95 static int update_working_directory(struct pattern_list *pl)
96 {
97         int result = 0;
98         struct unpack_trees_options o;
99         struct lock_file lock_file = LOCK_INIT;
100         struct object_id oid;
101         struct tree *tree;
102         struct tree_desc t;
103         struct repository *r = the_repository;
104
105         if (repo_read_index_unmerged(r))
106                 die(_("you need to resolve your current index first"));
107
108         if (get_oid("HEAD", &oid))
109                 return 0;
110
111         tree = parse_tree_indirect(&oid);
112         parse_tree(tree);
113         init_tree_desc(&t, tree->buffer, tree->size);
114
115         memset(&o, 0, sizeof(o));
116         o.verbose_update = isatty(2);
117         o.merge = 1;
118         o.update = 1;
119         o.fn = oneway_merge;
120         o.head_idx = -1;
121         o.src_index = r->index;
122         o.dst_index = r->index;
123         o.skip_sparse_checkout = 0;
124         o.pl = pl;
125
126         resolve_undo_clear_index(r->index);
127         setup_work_tree();
128
129         cache_tree_free(&r->index->cache_tree);
130
131         repo_hold_locked_index(r, &lock_file, LOCK_DIE_ON_ERROR);
132
133         core_apply_sparse_checkout = 1;
134         result = unpack_trees(1, &t, &o);
135
136         if (!result) {
137                 prime_cache_tree(r, r->index, tree);
138                 write_locked_index(r->index, &lock_file, COMMIT_LOCK);
139         } else
140                 rollback_lock_file(&lock_file);
141
142         return result;
143 }
144
145 static char *escaped_pattern(char *pattern)
146 {
147         char *p = pattern;
148         struct strbuf final = STRBUF_INIT;
149
150         while (*p) {
151                 if (is_glob_special(*p))
152                         strbuf_addch(&final, '\\');
153
154                 strbuf_addch(&final, *p);
155                 p++;
156         }
157
158         return strbuf_detach(&final, NULL);
159 }
160
161 static void write_cone_to_file(FILE *fp, struct pattern_list *pl)
162 {
163         int i;
164         struct pattern_entry *pe;
165         struct hashmap_iter iter;
166         struct string_list sl = STRING_LIST_INIT_DUP;
167         struct strbuf parent_pattern = STRBUF_INIT;
168
169         hashmap_for_each_entry(&pl->parent_hashmap, &iter, pe, ent) {
170                 if (hashmap_get_entry(&pl->recursive_hashmap, pe, ent, NULL))
171                         continue;
172
173                 if (!hashmap_contains_parent(&pl->recursive_hashmap,
174                                              pe->pattern,
175                                              &parent_pattern))
176                         string_list_insert(&sl, pe->pattern);
177         }
178
179         string_list_sort(&sl);
180         string_list_remove_duplicates(&sl, 0);
181
182         fprintf(fp, "/*\n!/*/\n");
183
184         for (i = 0; i < sl.nr; i++) {
185                 char *pattern = escaped_pattern(sl.items[i].string);
186
187                 if (strlen(pattern))
188                         fprintf(fp, "%s/\n!%s/*/\n", pattern, pattern);
189                 free(pattern);
190         }
191
192         string_list_clear(&sl, 0);
193
194         hashmap_for_each_entry(&pl->recursive_hashmap, &iter, pe, ent) {
195                 if (!hashmap_contains_parent(&pl->recursive_hashmap,
196                                              pe->pattern,
197                                              &parent_pattern))
198                         string_list_insert(&sl, pe->pattern);
199         }
200
201         strbuf_release(&parent_pattern);
202
203         string_list_sort(&sl);
204         string_list_remove_duplicates(&sl, 0);
205
206         for (i = 0; i < sl.nr; i++) {
207                 char *pattern = escaped_pattern(sl.items[i].string);
208                 fprintf(fp, "%s/\n", pattern);
209                 free(pattern);
210         }
211 }
212
213 static int write_patterns_and_update(struct pattern_list *pl)
214 {
215         char *sparse_filename;
216         FILE *fp;
217         int fd;
218         struct lock_file lk = LOCK_INIT;
219         int result;
220
221         sparse_filename = get_sparse_checkout_filename();
222
223         if (safe_create_leading_directories(sparse_filename))
224                 die(_("failed to create directory for sparse-checkout file"));
225
226         fd = hold_lock_file_for_update(&lk, sparse_filename,
227                                       LOCK_DIE_ON_ERROR);
228
229         result = update_working_directory(pl);
230         if (result) {
231                 rollback_lock_file(&lk);
232                 free(sparse_filename);
233                 clear_pattern_list(pl);
234                 update_working_directory(NULL);
235                 return result;
236         }
237
238         fp = xfdopen(fd, "w");
239
240         if (core_sparse_checkout_cone)
241                 write_cone_to_file(fp, pl);
242         else
243                 write_patterns_to_file(fp, pl);
244
245         fflush(fp);
246         commit_lock_file(&lk);
247
248         free(sparse_filename);
249         clear_pattern_list(pl);
250
251         return 0;
252 }
253
254 enum sparse_checkout_mode {
255         MODE_NO_PATTERNS = 0,
256         MODE_ALL_PATTERNS = 1,
257         MODE_CONE_PATTERNS = 2,
258 };
259
260 static int set_config(enum sparse_checkout_mode mode)
261 {
262         const char *config_path;
263
264         if (git_config_set_gently("extensions.worktreeConfig", "true")) {
265                 error(_("failed to set extensions.worktreeConfig setting"));
266                 return 1;
267         }
268
269         config_path = git_path("config.worktree");
270         git_config_set_in_file_gently(config_path,
271                                       "core.sparseCheckout",
272                                       mode ? "true" : NULL);
273
274         git_config_set_in_file_gently(config_path,
275                                       "core.sparseCheckoutCone",
276                                       mode == MODE_CONE_PATTERNS ? "true" : NULL);
277
278         return 0;
279 }
280
281 static char const * const builtin_sparse_checkout_init_usage[] = {
282         N_("git sparse-checkout init [--cone]"),
283         NULL
284 };
285
286 static struct sparse_checkout_init_opts {
287         int cone_mode;
288 } init_opts;
289
290 static int sparse_checkout_init(int argc, const char **argv)
291 {
292         struct pattern_list pl;
293         char *sparse_filename;
294         int res;
295         struct object_id oid;
296         int mode;
297         struct strbuf pattern = STRBUF_INIT;
298
299         static struct option builtin_sparse_checkout_init_options[] = {
300                 OPT_BOOL(0, "cone", &init_opts.cone_mode,
301                          N_("initialize the sparse-checkout in cone mode")),
302                 OPT_END(),
303         };
304
305         repo_read_index(the_repository);
306         require_clean_work_tree(the_repository,
307                                 N_("initialize sparse-checkout"), NULL, 1, 0);
308
309         argc = parse_options(argc, argv, NULL,
310                              builtin_sparse_checkout_init_options,
311                              builtin_sparse_checkout_init_usage, 0);
312
313         if (init_opts.cone_mode) {
314                 mode = MODE_CONE_PATTERNS;
315                 core_sparse_checkout_cone = 1;
316         } else
317                 mode = MODE_ALL_PATTERNS;
318
319         if (set_config(mode))
320                 return 1;
321
322         memset(&pl, 0, sizeof(pl));
323
324         sparse_filename = get_sparse_checkout_filename();
325         res = add_patterns_from_file_to_list(sparse_filename, "", 0, &pl, NULL);
326
327         /* If we already have a sparse-checkout file, use it. */
328         if (res >= 0) {
329                 free(sparse_filename);
330                 core_apply_sparse_checkout = 1;
331                 return update_working_directory(NULL);
332         }
333
334         if (get_oid("HEAD", &oid)) {
335                 FILE *fp;
336
337                 /* assume we are in a fresh repo, but update the sparse-checkout file */
338                 fp = xfopen(sparse_filename, "w");
339                 if (!fp)
340                         die(_("failed to open '%s'"), sparse_filename);
341
342                 free(sparse_filename);
343                 fprintf(fp, "/*\n!/*/\n");
344                 fclose(fp);
345                 return 0;
346         }
347
348         strbuf_addstr(&pattern, "/*");
349         add_pattern(strbuf_detach(&pattern, NULL), empty_base, 0, &pl, 0);
350         strbuf_addstr(&pattern, "!/*/");
351         add_pattern(strbuf_detach(&pattern, NULL), empty_base, 0, &pl, 0);
352
353         return write_patterns_and_update(&pl);
354 }
355
356 static void insert_recursive_pattern(struct pattern_list *pl, struct strbuf *path)
357 {
358         struct pattern_entry *e = xmalloc(sizeof(*e));
359         e->patternlen = path->len;
360         e->pattern = strbuf_detach(path, NULL);
361         hashmap_entry_init(&e->ent,
362                            ignore_case ?
363                            strihash(e->pattern) :
364                            strhash(e->pattern));
365
366         hashmap_add(&pl->recursive_hashmap, &e->ent);
367
368         while (e->patternlen) {
369                 char *slash = strrchr(e->pattern, '/');
370                 char *oldpattern = e->pattern;
371                 size_t newlen;
372
373                 if (slash == e->pattern)
374                         break;
375
376                 newlen = slash - e->pattern;
377                 e = xmalloc(sizeof(struct pattern_entry));
378                 e->patternlen = newlen;
379                 e->pattern = xstrndup(oldpattern, newlen);
380                 hashmap_entry_init(&e->ent,
381                                    ignore_case ?
382                                    strihash(e->pattern) :
383                                    strhash(e->pattern));
384
385                 if (!hashmap_get_entry(&pl->parent_hashmap, e, ent, NULL))
386                         hashmap_add(&pl->parent_hashmap, &e->ent);
387         }
388 }
389
390 static void strbuf_to_cone_pattern(struct strbuf *line, struct pattern_list *pl)
391 {
392         strbuf_trim(line);
393
394         strbuf_trim_trailing_dir_sep(line);
395
396         if (strbuf_normalize_path(line))
397                 die(_("could not normalize path %s"), line->buf);
398
399         if (!line->len)
400                 return;
401
402         if (line->buf[0] != '/')
403                 strbuf_insertstr(line, 0, "/");
404
405         insert_recursive_pattern(pl, line);
406 }
407
408 static char const * const builtin_sparse_checkout_set_usage[] = {
409         N_("git sparse-checkout (set|add) (--stdin | <patterns>)"),
410         NULL
411 };
412
413 static struct sparse_checkout_set_opts {
414         int use_stdin;
415 } set_opts;
416
417 static void add_patterns_from_input(struct pattern_list *pl,
418                                     int argc, const char **argv)
419 {
420         int i;
421         if (core_sparse_checkout_cone) {
422                 struct strbuf line = STRBUF_INIT;
423
424                 hashmap_init(&pl->recursive_hashmap, pl_hashmap_cmp, NULL, 0);
425                 hashmap_init(&pl->parent_hashmap, pl_hashmap_cmp, NULL, 0);
426                 pl->use_cone_patterns = 1;
427
428                 if (set_opts.use_stdin) {
429                         struct strbuf unquoted = STRBUF_INIT;
430                         while (!strbuf_getline(&line, stdin)) {
431                                 if (line.buf[0] == '"') {
432                                         strbuf_reset(&unquoted);
433                                         if (unquote_c_style(&unquoted, line.buf, NULL))
434                                                 die(_("unable to unquote C-style string '%s'"),
435                                                 line.buf);
436
437                                         strbuf_swap(&unquoted, &line);
438                                 }
439
440                                 strbuf_to_cone_pattern(&line, pl);
441                         }
442
443                         strbuf_release(&unquoted);
444                 } else {
445                         for (i = 0; i < argc; i++) {
446                                 strbuf_setlen(&line, 0);
447                                 strbuf_addstr(&line, argv[i]);
448                                 strbuf_to_cone_pattern(&line, pl);
449                         }
450                 }
451         } else {
452                 if (set_opts.use_stdin) {
453                         struct strbuf line = STRBUF_INIT;
454
455                         while (!strbuf_getline(&line, stdin)) {
456                                 size_t len;
457                                 char *buf = strbuf_detach(&line, &len);
458                                 add_pattern(buf, empty_base, 0, pl, 0);
459                         }
460                 } else {
461                         for (i = 0; i < argc; i++)
462                                 add_pattern(argv[i], empty_base, 0, pl, 0);
463                 }
464         }
465 }
466
467 enum modify_type {
468         REPLACE,
469         ADD,
470 };
471
472 static void add_patterns_cone_mode(int argc, const char **argv,
473                                    struct pattern_list *pl)
474 {
475         struct strbuf buffer = STRBUF_INIT;
476         struct pattern_entry *pe;
477         struct hashmap_iter iter;
478         struct pattern_list existing;
479         char *sparse_filename = get_sparse_checkout_filename();
480
481         add_patterns_from_input(pl, argc, argv);
482
483         memset(&existing, 0, sizeof(existing));
484         existing.use_cone_patterns = core_sparse_checkout_cone;
485
486         if (add_patterns_from_file_to_list(sparse_filename, "", 0,
487                                            &existing, NULL))
488                 die(_("unable to load existing sparse-checkout patterns"));
489         free(sparse_filename);
490
491         hashmap_for_each_entry(&existing.recursive_hashmap, &iter, pe, ent) {
492                 if (!hashmap_contains_parent(&pl->recursive_hashmap,
493                                         pe->pattern, &buffer) ||
494                     !hashmap_contains_parent(&pl->parent_hashmap,
495                                         pe->pattern, &buffer)) {
496                         strbuf_reset(&buffer);
497                         strbuf_addstr(&buffer, pe->pattern);
498                         insert_recursive_pattern(pl, &buffer);
499                 }
500         }
501
502         clear_pattern_list(&existing);
503         strbuf_release(&buffer);
504 }
505
506 static void add_patterns_literal(int argc, const char **argv,
507                                  struct pattern_list *pl)
508 {
509         char *sparse_filename = get_sparse_checkout_filename();
510         if (add_patterns_from_file_to_list(sparse_filename, "", 0,
511                                            pl, NULL))
512                 die(_("unable to load existing sparse-checkout patterns"));
513         free(sparse_filename);
514         add_patterns_from_input(pl, argc, argv);
515 }
516
517 static int modify_pattern_list(int argc, const char **argv, enum modify_type m)
518 {
519         int result;
520         int changed_config = 0;
521         struct pattern_list pl;
522         memset(&pl, 0, sizeof(pl));
523
524         switch (m) {
525         case ADD:
526                 if (core_sparse_checkout_cone)
527                         add_patterns_cone_mode(argc, argv, &pl);
528                 else
529                         add_patterns_literal(argc, argv, &pl);
530                 break;
531
532         case REPLACE:
533                 add_patterns_from_input(&pl, argc, argv);
534                 break;
535         }
536
537         if (!core_apply_sparse_checkout) {
538                 set_config(MODE_ALL_PATTERNS);
539                 core_apply_sparse_checkout = 1;
540                 changed_config = 1;
541         }
542
543         result = write_patterns_and_update(&pl);
544
545         if (result && changed_config)
546                 set_config(MODE_NO_PATTERNS);
547
548         clear_pattern_list(&pl);
549         return result;
550 }
551
552 static int sparse_checkout_set(int argc, const char **argv, const char *prefix,
553                                enum modify_type m)
554 {
555         static struct option builtin_sparse_checkout_set_options[] = {
556                 OPT_BOOL(0, "stdin", &set_opts.use_stdin,
557                          N_("read patterns from standard in")),
558                 OPT_END(),
559         };
560
561         repo_read_index(the_repository);
562         require_clean_work_tree(the_repository,
563                                 N_("set sparse-checkout patterns"), NULL, 1, 0);
564
565         argc = parse_options(argc, argv, prefix,
566                              builtin_sparse_checkout_set_options,
567                              builtin_sparse_checkout_set_usage,
568                              PARSE_OPT_KEEP_UNKNOWN);
569
570         return modify_pattern_list(argc, argv, m);
571 }
572
573 static int sparse_checkout_disable(int argc, const char **argv)
574 {
575         struct pattern_list pl;
576         struct strbuf match_all = STRBUF_INIT;
577
578         repo_read_index(the_repository);
579         require_clean_work_tree(the_repository,
580                                 N_("disable sparse-checkout"), NULL, 1, 0);
581
582         memset(&pl, 0, sizeof(pl));
583         hashmap_init(&pl.recursive_hashmap, pl_hashmap_cmp, NULL, 0);
584         hashmap_init(&pl.parent_hashmap, pl_hashmap_cmp, NULL, 0);
585         pl.use_cone_patterns = 0;
586         core_apply_sparse_checkout = 1;
587
588         strbuf_addstr(&match_all, "/*");
589         add_pattern(strbuf_detach(&match_all, NULL), empty_base, 0, &pl, 0);
590
591         if (update_working_directory(&pl))
592                 die(_("error while refreshing working directory"));
593
594         clear_pattern_list(&pl);
595         return set_config(MODE_NO_PATTERNS);
596 }
597
598 int cmd_sparse_checkout(int argc, const char **argv, const char *prefix)
599 {
600         static struct option builtin_sparse_checkout_options[] = {
601                 OPT_END(),
602         };
603
604         if (argc == 2 && !strcmp(argv[1], "-h"))
605                 usage_with_options(builtin_sparse_checkout_usage,
606                                    builtin_sparse_checkout_options);
607
608         argc = parse_options(argc, argv, prefix,
609                              builtin_sparse_checkout_options,
610                              builtin_sparse_checkout_usage,
611                              PARSE_OPT_STOP_AT_NON_OPTION);
612
613         git_config(git_default_config, NULL);
614
615         if (argc > 0) {
616                 if (!strcmp(argv[0], "list"))
617                         return sparse_checkout_list(argc, argv);
618                 if (!strcmp(argv[0], "init"))
619                         return sparse_checkout_init(argc, argv);
620                 if (!strcmp(argv[0], "set"))
621                         return sparse_checkout_set(argc, argv, prefix, REPLACE);
622                 if (!strcmp(argv[0], "add"))
623                         return sparse_checkout_set(argc, argv, prefix, ADD);
624                 if (!strcmp(argv[0], "disable"))
625                         return sparse_checkout_disable(argc, argv);
626         }
627
628         usage_with_options(builtin_sparse_checkout_usage,
629                            builtin_sparse_checkout_options);
630 }