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