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