Merge branch 'kn/for-each-tag-branch'
[git] / builtin / submodule--helper.c
1 #include "builtin.h"
2 #include "cache.h"
3 #include "parse-options.h"
4 #include "quote.h"
5 #include "pathspec.h"
6 #include "dir.h"
7 #include "utf8.h"
8 #include "submodule.h"
9 #include "submodule-config.h"
10 #include "string-list.h"
11 #include "run-command.h"
12
13 struct module_list {
14         const struct cache_entry **entries;
15         int alloc, nr;
16 };
17 #define MODULE_LIST_INIT { NULL, 0, 0 }
18
19 static int module_list_compute(int argc, const char **argv,
20                                const char *prefix,
21                                struct pathspec *pathspec,
22                                struct module_list *list)
23 {
24         int i, result = 0;
25         char *ps_matched = NULL;
26         parse_pathspec(pathspec, 0,
27                        PATHSPEC_PREFER_FULL |
28                        PATHSPEC_STRIP_SUBMODULE_SLASH_CHEAP,
29                        prefix, argv);
30
31         if (pathspec->nr)
32                 ps_matched = xcalloc(pathspec->nr, 1);
33
34         if (read_cache() < 0)
35                 die(_("index file corrupt"));
36
37         for (i = 0; i < active_nr; i++) {
38                 const struct cache_entry *ce = active_cache[i];
39
40                 if (!match_pathspec(pathspec, ce->name, ce_namelen(ce),
41                                     0, ps_matched, 1) ||
42                     !S_ISGITLINK(ce->ce_mode))
43                         continue;
44
45                 ALLOC_GROW(list->entries, list->nr + 1, list->alloc);
46                 list->entries[list->nr++] = ce;
47                 while (i + 1 < active_nr &&
48                        !strcmp(ce->name, active_cache[i + 1]->name))
49                         /*
50                          * Skip entries with the same name in different stages
51                          * to make sure an entry is returned only once.
52                          */
53                         i++;
54         }
55
56         if (ps_matched && report_path_error(ps_matched, pathspec, prefix))
57                 result = -1;
58
59         free(ps_matched);
60
61         return result;
62 }
63
64 static int module_list(int argc, const char **argv, const char *prefix)
65 {
66         int i;
67         struct pathspec pathspec;
68         struct module_list list = MODULE_LIST_INIT;
69
70         struct option module_list_options[] = {
71                 OPT_STRING(0, "prefix", &prefix,
72                            N_("path"),
73                            N_("alternative anchor for relative paths")),
74                 OPT_END()
75         };
76
77         const char *const git_submodule_helper_usage[] = {
78                 N_("git submodule--helper list [--prefix=<path>] [<path>...]"),
79                 NULL
80         };
81
82         argc = parse_options(argc, argv, prefix, module_list_options,
83                              git_submodule_helper_usage, 0);
84
85         if (module_list_compute(argc, argv, prefix, &pathspec, &list) < 0) {
86                 printf("#unmatched\n");
87                 return 1;
88         }
89
90         for (i = 0; i < list.nr; i++) {
91                 const struct cache_entry *ce = list.entries[i];
92
93                 if (ce_stage(ce))
94                         printf("%06o %s U\t", ce->ce_mode, sha1_to_hex(null_sha1));
95                 else
96                         printf("%06o %s %d\t", ce->ce_mode, sha1_to_hex(ce->sha1), ce_stage(ce));
97
98                 utf8_fprintf(stdout, "%s\n", ce->name);
99         }
100         return 0;
101 }
102
103 static int module_name(int argc, const char **argv, const char *prefix)
104 {
105         const struct submodule *sub;
106
107         if (argc != 2)
108                 usage(_("git submodule--helper name <path>"));
109
110         gitmodules_config();
111         sub = submodule_from_path(null_sha1, argv[1]);
112
113         if (!sub)
114                 die(_("no submodule mapping found in .gitmodules for path '%s'"),
115                     argv[1]);
116
117         printf("%s\n", sub->name);
118
119         return 0;
120 }
121
122 /*
123  * Rules to sanitize configuration variables that are Ok to be passed into
124  * submodule operations from the parent project using "-c". Should only
125  * include keys which are both (a) safe and (b) necessary for proper
126  * operation.
127  */
128 static int submodule_config_ok(const char *var)
129 {
130         if (starts_with(var, "credential."))
131                 return 1;
132         return 0;
133 }
134
135 static int sanitize_submodule_config(const char *var, const char *value, void *data)
136 {
137         struct strbuf *out = data;
138
139         if (submodule_config_ok(var)) {
140                 if (out->len)
141                         strbuf_addch(out, ' ');
142
143                 if (value)
144                         sq_quotef(out, "%s=%s", var, value);
145                 else
146                         sq_quote_buf(out, var);
147         }
148
149         return 0;
150 }
151
152 static void prepare_submodule_repo_env(struct argv_array *out)
153 {
154         const char * const *var;
155
156         for (var = local_repo_env; *var; var++) {
157                 if (!strcmp(*var, CONFIG_DATA_ENVIRONMENT)) {
158                         struct strbuf sanitized_config = STRBUF_INIT;
159                         git_config_from_parameters(sanitize_submodule_config,
160                                                    &sanitized_config);
161                         argv_array_pushf(out, "%s=%s", *var, sanitized_config.buf);
162                         strbuf_release(&sanitized_config);
163                 } else {
164                         argv_array_push(out, *var);
165                 }
166         }
167
168 }
169
170 static int clone_submodule(const char *path, const char *gitdir, const char *url,
171                            const char *depth, const char *reference, int quiet)
172 {
173         struct child_process cp;
174         child_process_init(&cp);
175
176         argv_array_push(&cp.args, "clone");
177         argv_array_push(&cp.args, "--no-checkout");
178         if (quiet)
179                 argv_array_push(&cp.args, "--quiet");
180         if (depth && *depth)
181                 argv_array_pushl(&cp.args, "--depth", depth, NULL);
182         if (reference && *reference)
183                 argv_array_pushl(&cp.args, "--reference", reference, NULL);
184         if (gitdir && *gitdir)
185                 argv_array_pushl(&cp.args, "--separate-git-dir", gitdir, NULL);
186
187         argv_array_push(&cp.args, url);
188         argv_array_push(&cp.args, path);
189
190         cp.git_cmd = 1;
191         prepare_submodule_repo_env(&cp.env_array);
192         cp.no_stdin = 1;
193
194         return run_command(&cp);
195 }
196
197 static int module_clone(int argc, const char **argv, const char *prefix)
198 {
199         const char *path = NULL, *name = NULL, *url = NULL;
200         const char *reference = NULL, *depth = NULL;
201         int quiet = 0;
202         FILE *submodule_dot_git;
203         char *sm_gitdir, *cwd, *p;
204         struct strbuf rel_path = STRBUF_INIT;
205         struct strbuf sb = STRBUF_INIT;
206
207         struct option module_clone_options[] = {
208                 OPT_STRING(0, "prefix", &prefix,
209                            N_("path"),
210                            N_("alternative anchor for relative paths")),
211                 OPT_STRING(0, "path", &path,
212                            N_("path"),
213                            N_("where the new submodule will be cloned to")),
214                 OPT_STRING(0, "name", &name,
215                            N_("string"),
216                            N_("name of the new submodule")),
217                 OPT_STRING(0, "url", &url,
218                            N_("string"),
219                            N_("url where to clone the submodule from")),
220                 OPT_STRING(0, "reference", &reference,
221                            N_("string"),
222                            N_("reference repository")),
223                 OPT_STRING(0, "depth", &depth,
224                            N_("string"),
225                            N_("depth for shallow clones")),
226                 OPT__QUIET(&quiet, "Suppress output for cloning a submodule"),
227                 OPT_END()
228         };
229
230         const char *const git_submodule_helper_usage[] = {
231                 N_("git submodule--helper clone [--prefix=<path>] [--quiet] "
232                    "[--reference <repository>] [--name <name>] [--depth <depth>] "
233                    "--url <url> --path <path>"),
234                 NULL
235         };
236
237         argc = parse_options(argc, argv, prefix, module_clone_options,
238                              git_submodule_helper_usage, 0);
239
240         if (argc || !url || !path)
241                 usage_with_options(git_submodule_helper_usage,
242                                    module_clone_options);
243
244         strbuf_addf(&sb, "%s/modules/%s", get_git_dir(), name);
245         sm_gitdir = strbuf_detach(&sb, NULL);
246
247         if (!file_exists(sm_gitdir)) {
248                 if (safe_create_leading_directories_const(sm_gitdir) < 0)
249                         die(_("could not create directory '%s'"), sm_gitdir);
250                 if (clone_submodule(path, sm_gitdir, url, depth, reference, quiet))
251                         die(_("clone of '%s' into submodule path '%s' failed"),
252                             url, path);
253         } else {
254                 if (safe_create_leading_directories_const(path) < 0)
255                         die(_("could not create directory '%s'"), path);
256                 strbuf_addf(&sb, "%s/index", sm_gitdir);
257                 unlink_or_warn(sb.buf);
258                 strbuf_reset(&sb);
259         }
260
261         /* Write a .git file in the submodule to redirect to the superproject. */
262         if (safe_create_leading_directories_const(path) < 0)
263                 die(_("could not create directory '%s'"), path);
264
265         if (path && *path)
266                 strbuf_addf(&sb, "%s/.git", path);
267         else
268                 strbuf_addstr(&sb, ".git");
269
270         if (safe_create_leading_directories_const(sb.buf) < 0)
271                 die(_("could not create leading directories of '%s'"), sb.buf);
272         submodule_dot_git = fopen(sb.buf, "w");
273         if (!submodule_dot_git)
274                 die_errno(_("cannot open file '%s'"), sb.buf);
275
276         fprintf(submodule_dot_git, "gitdir: %s\n",
277                 relative_path(sm_gitdir, path, &rel_path));
278         if (fclose(submodule_dot_git))
279                 die(_("could not close file %s"), sb.buf);
280         strbuf_reset(&sb);
281         strbuf_reset(&rel_path);
282
283         cwd = xgetcwd();
284         /* Redirect the worktree of the submodule in the superproject's config */
285         if (!is_absolute_path(sm_gitdir)) {
286                 strbuf_addf(&sb, "%s/%s", cwd, sm_gitdir);
287                 free(sm_gitdir);
288                 sm_gitdir = strbuf_detach(&sb, NULL);
289         }
290
291         strbuf_addf(&sb, "%s/%s", cwd, path);
292         p = git_pathdup_submodule(path, "config");
293         if (!p)
294                 die(_("could not get submodule directory for '%s'"), path);
295         git_config_set_in_file(p, "core.worktree",
296                                relative_path(sb.buf, sm_gitdir, &rel_path));
297         strbuf_release(&sb);
298         strbuf_release(&rel_path);
299         free(sm_gitdir);
300         free(cwd);
301         free(p);
302         return 0;
303 }
304
305 static int module_sanitize_config(int argc, const char **argv, const char *prefix)
306 {
307         struct strbuf sanitized_config = STRBUF_INIT;
308
309         if (argc > 1)
310                 usage(_("git submodule--helper sanitize-config"));
311
312         git_config_from_parameters(sanitize_submodule_config, &sanitized_config);
313         if (sanitized_config.len)
314                 printf("%s\n", sanitized_config.buf);
315
316         strbuf_release(&sanitized_config);
317
318         return 0;
319 }
320
321 struct submodule_update_clone {
322         /* index into 'list', the list of submodules to look into for cloning */
323         int current;
324         struct module_list list;
325         unsigned warn_if_uninitialized : 1;
326
327         /* update parameter passed via commandline */
328         struct submodule_update_strategy update;
329
330         /* configuration parameters which are passed on to the children */
331         int quiet;
332         const char *reference;
333         const char *depth;
334         const char *recursive_prefix;
335         const char *prefix;
336
337         /* Machine-readable status lines to be consumed by git-submodule.sh */
338         struct string_list projectlines;
339
340         /* If we want to stop as fast as possible and return an error */
341         unsigned quickstop : 1;
342 };
343 #define SUBMODULE_UPDATE_CLONE_INIT {0, MODULE_LIST_INIT, 0, \
344         SUBMODULE_UPDATE_STRATEGY_INIT, 0, NULL, NULL, NULL, NULL, \
345         STRING_LIST_INIT_DUP, 0}
346
347 /**
348  * Determine whether 'ce' needs to be cloned. If so, prepare the 'child' to
349  * run the clone. Returns 1 if 'ce' needs to be cloned, 0 otherwise.
350  */
351 static int prepare_to_clone_next_submodule(const struct cache_entry *ce,
352                                            struct child_process *child,
353                                            struct submodule_update_clone *suc,
354                                            struct strbuf *out)
355 {
356         const struct submodule *sub = NULL;
357         struct strbuf displaypath_sb = STRBUF_INIT;
358         struct strbuf sb = STRBUF_INIT;
359         const char *displaypath = NULL;
360         char *url = NULL;
361         int needs_cloning = 0;
362
363         if (ce_stage(ce)) {
364                 if (suc->recursive_prefix)
365                         strbuf_addf(&sb, "%s/%s", suc->recursive_prefix, ce->name);
366                 else
367                         strbuf_addf(&sb, "%s", ce->name);
368                 strbuf_addf(out, _("Skipping unmerged submodule %s"), sb.buf);
369                 strbuf_addch(out, '\n');
370                 goto cleanup;
371         }
372
373         sub = submodule_from_path(null_sha1, ce->name);
374
375         if (suc->recursive_prefix)
376                 displaypath = relative_path(suc->recursive_prefix,
377                                             ce->name, &displaypath_sb);
378         else
379                 displaypath = ce->name;
380
381         if (suc->update.type == SM_UPDATE_NONE
382             || (suc->update.type == SM_UPDATE_UNSPECIFIED
383                 && sub->update_strategy.type == SM_UPDATE_NONE)) {
384                 strbuf_addf(out, _("Skipping submodule '%s'"), displaypath);
385                 strbuf_addch(out, '\n');
386                 goto cleanup;
387         }
388
389         /*
390          * Looking up the url in .git/config.
391          * We must not fall back to .gitmodules as we only want
392          * to process configured submodules.
393          */
394         strbuf_reset(&sb);
395         strbuf_addf(&sb, "submodule.%s.url", sub->name);
396         git_config_get_string(sb.buf, &url);
397         if (!url) {
398                 /*
399                  * Only mention uninitialized submodules when their
400                  * path have been specified
401                  */
402                 if (suc->warn_if_uninitialized) {
403                         strbuf_addf(out,
404                                 _("Submodule path '%s' not initialized"),
405                                 displaypath);
406                         strbuf_addch(out, '\n');
407                         strbuf_addstr(out,
408                                 _("Maybe you want to use 'update --init'?"));
409                         strbuf_addch(out, '\n');
410                 }
411                 goto cleanup;
412         }
413
414         strbuf_reset(&sb);
415         strbuf_addf(&sb, "%s/.git", ce->name);
416         needs_cloning = !file_exists(sb.buf);
417
418         strbuf_reset(&sb);
419         strbuf_addf(&sb, "%06o %s %d %d\t%s\n", ce->ce_mode,
420                         sha1_to_hex(ce->sha1), ce_stage(ce),
421                         needs_cloning, ce->name);
422         string_list_append(&suc->projectlines, sb.buf);
423
424         if (!needs_cloning)
425                 goto cleanup;
426
427         child->git_cmd = 1;
428         child->no_stdin = 1;
429         child->stdout_to_stderr = 1;
430         child->err = -1;
431         argv_array_push(&child->args, "submodule--helper");
432         argv_array_push(&child->args, "clone");
433         if (suc->quiet)
434                 argv_array_push(&child->args, "--quiet");
435         if (suc->prefix)
436                 argv_array_pushl(&child->args, "--prefix", suc->prefix, NULL);
437         argv_array_pushl(&child->args, "--path", sub->path, NULL);
438         argv_array_pushl(&child->args, "--name", sub->name, NULL);
439         argv_array_pushl(&child->args, "--url", url, NULL);
440         if (suc->reference)
441                 argv_array_push(&child->args, suc->reference);
442         if (suc->depth)
443                 argv_array_push(&child->args, suc->depth);
444
445 cleanup:
446         free(url);
447         strbuf_reset(&displaypath_sb);
448         strbuf_reset(&sb);
449
450         return needs_cloning;
451 }
452
453 static int update_clone_get_next_task(struct child_process *child,
454                                       struct strbuf *err,
455                                       void *suc_cb,
456                                       void **void_task_cb)
457 {
458         struct submodule_update_clone *suc = suc_cb;
459
460         for (; suc->current < suc->list.nr; suc->current++) {
461                 const struct cache_entry *ce = suc->list.entries[suc->current];
462                 if (prepare_to_clone_next_submodule(ce, child, suc, err)) {
463                         suc->current++;
464                         return 1;
465                 }
466         }
467         return 0;
468 }
469
470 static int update_clone_start_failure(struct strbuf *err,
471                                       void *suc_cb,
472                                       void *void_task_cb)
473 {
474         struct submodule_update_clone *suc = suc_cb;
475         suc->quickstop = 1;
476         return 1;
477 }
478
479 static int update_clone_task_finished(int result,
480                                       struct strbuf *err,
481                                       void *suc_cb,
482                                       void *void_task_cb)
483 {
484         struct submodule_update_clone *suc = suc_cb;
485
486         if (!result)
487                 return 0;
488
489         suc->quickstop = 1;
490         return 1;
491 }
492
493 static int update_clone(int argc, const char **argv, const char *prefix)
494 {
495         const char *update = NULL;
496         int max_jobs = -1;
497         struct string_list_item *item;
498         struct pathspec pathspec;
499         struct submodule_update_clone suc = SUBMODULE_UPDATE_CLONE_INIT;
500
501         struct option module_update_clone_options[] = {
502                 OPT_STRING(0, "prefix", &prefix,
503                            N_("path"),
504                            N_("path into the working tree")),
505                 OPT_STRING(0, "recursive-prefix", &suc.recursive_prefix,
506                            N_("path"),
507                            N_("path into the working tree, across nested "
508                               "submodule boundaries")),
509                 OPT_STRING(0, "update", &update,
510                            N_("string"),
511                            N_("rebase, merge, checkout or none")),
512                 OPT_STRING(0, "reference", &suc.reference, N_("repo"),
513                            N_("reference repository")),
514                 OPT_STRING(0, "depth", &suc.depth, "<depth>",
515                            N_("Create a shallow clone truncated to the "
516                               "specified number of revisions")),
517                 OPT_INTEGER('j', "jobs", &max_jobs,
518                             N_("parallel jobs")),
519                 OPT__QUIET(&suc.quiet, N_("don't print cloning progress")),
520                 OPT_END()
521         };
522
523         const char *const git_submodule_helper_usage[] = {
524                 N_("git submodule--helper update_clone [--prefix=<path>] [<path>...]"),
525                 NULL
526         };
527         suc.prefix = prefix;
528
529         argc = parse_options(argc, argv, prefix, module_update_clone_options,
530                              git_submodule_helper_usage, 0);
531
532         if (update)
533                 if (parse_submodule_update_strategy(update, &suc.update) < 0)
534                         die(_("bad value for update parameter"));
535
536         if (module_list_compute(argc, argv, prefix, &pathspec, &suc.list) < 0)
537                 return 1;
538
539         if (pathspec.nr)
540                 suc.warn_if_uninitialized = 1;
541
542         /* Overlay the parsed .gitmodules file with .git/config */
543         gitmodules_config();
544         git_config(submodule_config, NULL);
545
546         if (max_jobs < 0)
547                 max_jobs = parallel_submodules();
548
549         run_processes_parallel(max_jobs,
550                                update_clone_get_next_task,
551                                update_clone_start_failure,
552                                update_clone_task_finished,
553                                &suc);
554
555         /*
556          * We saved the output and put it out all at once now.
557          * That means:
558          * - the listener does not have to interleave their (checkout)
559          *   work with our fetching.  The writes involved in a
560          *   checkout involve more straightforward sequential I/O.
561          * - the listener can avoid doing any work if fetching failed.
562          */
563         if (suc.quickstop)
564                 return 1;
565
566         for_each_string_list_item(item, &suc.projectlines)
567                 utf8_fprintf(stdout, "%s", item->string);
568
569         return 0;
570 }
571
572 struct cmd_struct {
573         const char *cmd;
574         int (*fn)(int, const char **, const char *);
575 };
576
577 static struct cmd_struct commands[] = {
578         {"list", module_list},
579         {"name", module_name},
580         {"clone", module_clone},
581         {"sanitize-config", module_sanitize_config},
582         {"update-clone", update_clone}
583 };
584
585 int cmd_submodule__helper(int argc, const char **argv, const char *prefix)
586 {
587         int i;
588         if (argc < 2)
589                 die(_("submodule--helper subcommand must be "
590                       "called with a subcommand"));
591
592         for (i = 0; i < ARRAY_SIZE(commands); i++)
593                 if (!strcmp(argv[1], commands[i].cmd))
594                         return commands[i].fn(argc - 1, argv + 1, prefix);
595
596         die(_("'%s' is not a valid submodule--helper "
597               "subcommand"), argv[1]);
598 }