Coverage Report

Created: 2023-11-19 07:08

/src/git/submodule.c
Line
Count
Source (jump to first uncovered line)
1
#include "git-compat-util.h"
2
#include "abspath.h"
3
#include "repository.h"
4
#include "config.h"
5
#include "submodule-config.h"
6
#include "submodule.h"
7
#include "dir.h"
8
#include "diff.h"
9
#include "commit.h"
10
#include "environment.h"
11
#include "gettext.h"
12
#include "hex.h"
13
#include "revision.h"
14
#include "run-command.h"
15
#include "diffcore.h"
16
#include "refs.h"
17
#include "string-list.h"
18
#include "oid-array.h"
19
#include "strvec.h"
20
#include "blob.h"
21
#include "thread-utils.h"
22
#include "path.h"
23
#include "quote.h"
24
#include "remote.h"
25
#include "worktree.h"
26
#include "parse-options.h"
27
#include "object-file.h"
28
#include "object-name.h"
29
#include "object-store-ll.h"
30
#include "commit-reach.h"
31
#include "read-cache-ll.h"
32
#include "setup.h"
33
#include "shallow.h"
34
#include "trace2.h"
35
36
static int config_update_recurse_submodules = RECURSE_SUBMODULES_OFF;
37
static int initialized_fetch_ref_tips;
38
static struct oid_array ref_tips_before_fetch;
39
static struct oid_array ref_tips_after_fetch;
40
41
/*
42
 * Check if the .gitmodules file is unmerged. Parsing of the .gitmodules file
43
 * will be disabled because we can't guess what might be configured in
44
 * .gitmodules unless the user resolves the conflict.
45
 */
46
int is_gitmodules_unmerged(struct index_state *istate)
47
0
{
48
0
  int pos = index_name_pos(istate, GITMODULES_FILE, strlen(GITMODULES_FILE));
49
0
  if (pos < 0) { /* .gitmodules not found or isn't merged */
50
0
    pos = -1 - pos;
51
0
    if (istate->cache_nr > pos) {  /* there is a .gitmodules */
52
0
      const struct cache_entry *ce = istate->cache[pos];
53
0
      if (ce_namelen(ce) == strlen(GITMODULES_FILE) &&
54
0
          !strcmp(ce->name, GITMODULES_FILE))
55
0
        return 1;
56
0
    }
57
0
  }
58
59
0
  return 0;
60
0
}
61
62
/*
63
 * Check if the .gitmodules file is safe to write.
64
 *
65
 * Writing to the .gitmodules file requires that the file exists in the
66
 * working tree or, if it doesn't, that a brand new .gitmodules file is going
67
 * to be created (i.e. it's neither in the index nor in the current branch).
68
 *
69
 * It is not safe to write to .gitmodules if it's not in the working tree but
70
 * it is in the index or in the current branch, because writing new values
71
 * (and staging them) would blindly overwrite ALL the old content.
72
 */
73
int is_writing_gitmodules_ok(void)
74
0
{
75
0
  struct object_id oid;
76
0
  return file_exists(GITMODULES_FILE) ||
77
0
    (repo_get_oid(the_repository, GITMODULES_INDEX, &oid) < 0 && repo_get_oid(the_repository, GITMODULES_HEAD, &oid) < 0);
78
0
}
79
80
/*
81
 * Check if the .gitmodules file has unstaged modifications.  This must be
82
 * checked before allowing modifications to the .gitmodules file with the
83
 * intention to stage them later, because when continuing we would stage the
84
 * modifications the user didn't stage herself too. That might change in a
85
 * future version when we learn to stage the changes we do ourselves without
86
 * staging any previous modifications.
87
 */
88
int is_staging_gitmodules_ok(struct index_state *istate)
89
0
{
90
0
  int pos = index_name_pos(istate, GITMODULES_FILE, strlen(GITMODULES_FILE));
91
92
0
  if ((pos >= 0) && (pos < istate->cache_nr)) {
93
0
    struct stat st;
94
0
    if (lstat(GITMODULES_FILE, &st) == 0 &&
95
0
        ie_modified(istate, istate->cache[pos], &st, 0) & DATA_CHANGED)
96
0
      return 0;
97
0
  }
98
99
0
  return 1;
100
0
}
101
102
static int for_each_remote_ref_submodule(const char *submodule,
103
           each_ref_fn fn, void *cb_data)
104
0
{
105
0
  return refs_for_each_remote_ref(get_submodule_ref_store(submodule),
106
0
          fn, cb_data);
107
0
}
108
109
/*
110
 * Try to update the "path" entry in the "submodule.<name>" section of the
111
 * .gitmodules file. Return 0 only if a .gitmodules file was found, a section
112
 * with the correct path=<oldpath> setting was found and we could update it.
113
 */
114
int update_path_in_gitmodules(const char *oldpath, const char *newpath)
115
0
{
116
0
  struct strbuf entry = STRBUF_INIT;
117
0
  const struct submodule *submodule;
118
0
  int ret;
119
120
0
  if (!file_exists(GITMODULES_FILE)) /* Do nothing without .gitmodules */
121
0
    return -1;
122
123
0
  if (is_gitmodules_unmerged(the_repository->index))
124
0
    die(_("Cannot change unmerged .gitmodules, resolve merge conflicts first"));
125
126
0
  submodule = submodule_from_path(the_repository, null_oid(), oldpath);
127
0
  if (!submodule || !submodule->name) {
128
0
    warning(_("Could not find section in .gitmodules where path=%s"), oldpath);
129
0
    return -1;
130
0
  }
131
0
  strbuf_addstr(&entry, "submodule.");
132
0
  strbuf_addstr(&entry, submodule->name);
133
0
  strbuf_addstr(&entry, ".path");
134
0
  ret = config_set_in_gitmodules_file_gently(entry.buf, newpath);
135
0
  strbuf_release(&entry);
136
0
  return ret;
137
0
}
138
139
/*
140
 * Try to remove the "submodule.<name>" section from .gitmodules where the given
141
 * path is configured. Return 0 only if a .gitmodules file was found, a section
142
 * with the correct path=<path> setting was found and we could remove it.
143
 */
144
int remove_path_from_gitmodules(const char *path)
145
0
{
146
0
  struct strbuf sect = STRBUF_INIT;
147
0
  const struct submodule *submodule;
148
149
0
  if (!file_exists(GITMODULES_FILE)) /* Do nothing without .gitmodules */
150
0
    return -1;
151
152
0
  if (is_gitmodules_unmerged(the_repository->index))
153
0
    die(_("Cannot change unmerged .gitmodules, resolve merge conflicts first"));
154
155
0
  submodule = submodule_from_path(the_repository, null_oid(), path);
156
0
  if (!submodule || !submodule->name) {
157
0
    warning(_("Could not find section in .gitmodules where path=%s"), path);
158
0
    return -1;
159
0
  }
160
0
  strbuf_addstr(&sect, "submodule.");
161
0
  strbuf_addstr(&sect, submodule->name);
162
0
  if (git_config_rename_section_in_file(GITMODULES_FILE, sect.buf, NULL) < 0) {
163
    /* Maybe the user already did that, don't error out here */
164
0
    warning(_("Could not remove .gitmodules entry for %s"), path);
165
0
    strbuf_release(&sect);
166
0
    return -1;
167
0
  }
168
0
  strbuf_release(&sect);
169
0
  return 0;
170
0
}
171
172
void stage_updated_gitmodules(struct index_state *istate)
173
0
{
174
0
  if (add_file_to_index(istate, GITMODULES_FILE, 0))
175
0
    die(_("staging updated .gitmodules failed"));
176
0
}
177
178
static struct string_list added_submodule_odb_paths = STRING_LIST_INIT_NODUP;
179
180
void add_submodule_odb_by_path(const char *path)
181
0
{
182
0
  string_list_insert(&added_submodule_odb_paths, xstrdup(path));
183
0
}
184
185
int register_all_submodule_odb_as_alternates(void)
186
0
{
187
0
  int i;
188
0
  int ret = added_submodule_odb_paths.nr;
189
190
0
  for (i = 0; i < added_submodule_odb_paths.nr; i++)
191
0
    add_to_alternates_memory(added_submodule_odb_paths.items[i].string);
192
0
  if (ret) {
193
0
    string_list_clear(&added_submodule_odb_paths, 0);
194
0
    trace2_data_intmax("submodule", the_repository,
195
0
           "register_all_submodule_odb_as_alternates/registered", ret);
196
0
    if (git_env_bool("GIT_TEST_FATAL_REGISTER_SUBMODULE_ODB", 0))
197
0
      BUG("register_all_submodule_odb_as_alternates() called");
198
0
  }
199
0
  return ret;
200
0
}
201
202
void set_diffopt_flags_from_submodule_config(struct diff_options *diffopt,
203
               const char *path)
204
0
{
205
0
  const struct submodule *submodule = submodule_from_path(the_repository,
206
0
                null_oid(),
207
0
                path);
208
0
  if (submodule) {
209
0
    const char *ignore;
210
0
    char *key;
211
212
0
    key = xstrfmt("submodule.%s.ignore", submodule->name);
213
0
    if (repo_config_get_string_tmp(the_repository, key, &ignore))
214
0
      ignore = submodule->ignore;
215
0
    free(key);
216
217
0
    if (ignore)
218
0
      handle_ignore_submodules_arg(diffopt, ignore);
219
0
    else if (is_gitmodules_unmerged(the_repository->index))
220
0
      diffopt->flags.ignore_submodules = 1;
221
0
  }
222
0
}
223
224
/* Cheap function that only determines if we're interested in submodules at all */
225
int git_default_submodule_config(const char *var, const char *value,
226
         void *cb UNUSED)
227
0
{
228
0
  if (!strcmp(var, "submodule.recurse")) {
229
0
    int v = git_config_bool(var, value) ?
230
0
      RECURSE_SUBMODULES_ON : RECURSE_SUBMODULES_OFF;
231
0
    config_update_recurse_submodules = v;
232
0
  }
233
0
  return 0;
234
0
}
235
236
int option_parse_recurse_submodules_worktree_updater(const struct option *opt,
237
                 const char *arg, int unset)
238
0
{
239
0
  if (unset) {
240
0
    config_update_recurse_submodules = RECURSE_SUBMODULES_OFF;
241
0
    return 0;
242
0
  }
243
0
  if (arg)
244
0
    config_update_recurse_submodules =
245
0
      parse_update_recurse_submodules_arg(opt->long_name,
246
0
                  arg);
247
0
  else
248
0
    config_update_recurse_submodules = RECURSE_SUBMODULES_ON;
249
250
0
  return 0;
251
0
}
252
253
/*
254
 * Determine if a submodule has been initialized at a given 'path'
255
 */
256
/*
257
 * NEEDSWORK: Emit a warning if submodule.active exists, but is valueless,
258
 * ie, the config looks like: "[submodule] active\n".
259
 * Since that is an invalid pathspec, we should inform the user.
260
 */
261
int is_tree_submodule_active(struct repository *repo,
262
           const struct object_id *treeish_name,
263
           const char *path)
264
0
{
265
0
  int ret = 0;
266
0
  char *key = NULL;
267
0
  char *value = NULL;
268
0
  const struct string_list *sl;
269
0
  const struct submodule *module;
270
271
0
  module = submodule_from_path(repo, treeish_name, path);
272
273
  /* early return if there isn't a path->module mapping */
274
0
  if (!module)
275
0
    return 0;
276
277
  /* submodule.<name>.active is set */
278
0
  key = xstrfmt("submodule.%s.active", module->name);
279
0
  if (!repo_config_get_bool(repo, key, &ret)) {
280
0
    free(key);
281
0
    return ret;
282
0
  }
283
0
  free(key);
284
285
  /* submodule.active is set */
286
0
  if (!repo_config_get_string_multi(repo, "submodule.active", &sl)) {
287
0
    struct pathspec ps;
288
0
    struct strvec args = STRVEC_INIT;
289
0
    const struct string_list_item *item;
290
291
0
    for_each_string_list_item(item, sl) {
292
0
      strvec_push(&args, item->string);
293
0
    }
294
295
0
    parse_pathspec(&ps, 0, 0, NULL, args.v);
296
0
    ret = match_pathspec(repo->index, &ps, path, strlen(path), 0, NULL, 1);
297
298
0
    strvec_clear(&args);
299
0
    clear_pathspec(&ps);
300
0
    return ret;
301
0
  }
302
303
  /* fallback to checking if the URL is set */
304
0
  key = xstrfmt("submodule.%s.url", module->name);
305
0
  ret = !repo_config_get_string(repo, key, &value);
306
307
0
  free(value);
308
0
  free(key);
309
0
  return ret;
310
0
}
311
312
int is_submodule_active(struct repository *repo, const char *path)
313
0
{
314
0
  return is_tree_submodule_active(repo, null_oid(), path);
315
0
}
316
317
int is_submodule_populated_gently(const char *path, int *return_error_code)
318
0
{
319
0
  int ret = 0;
320
0
  char *gitdir = xstrfmt("%s/.git", path);
321
322
0
  if (resolve_gitdir_gently(gitdir, return_error_code))
323
0
    ret = 1;
324
325
0
  free(gitdir);
326
0
  return ret;
327
0
}
328
329
/*
330
 * Dies if the provided 'prefix' corresponds to an unpopulated submodule
331
 */
332
void die_in_unpopulated_submodule(struct index_state *istate,
333
          const char *prefix)
334
7.32k
{
335
7.32k
  int i, prefixlen;
336
337
7.32k
  if (!prefix)
338
0
    return;
339
340
7.32k
  prefixlen = strlen(prefix);
341
342
49.2k
  for (i = 0; i < istate->cache_nr; i++) {
343
41.8k
    struct cache_entry *ce = istate->cache[i];
344
41.8k
    int ce_len = ce_namelen(ce);
345
346
41.8k
    if (!S_ISGITLINK(ce->ce_mode))
347
41.8k
      continue;
348
0
    if (prefixlen <= ce_len)
349
0
      continue;
350
0
    if (strncmp(ce->name, prefix, ce_len))
351
0
      continue;
352
0
    if (prefix[ce_len] != '/')
353
0
      continue;
354
355
0
    die(_("in unpopulated submodule '%s'"), ce->name);
356
0
  }
357
7.32k
}
358
359
/*
360
 * Dies if any paths in the provided pathspec descends into a submodule
361
 */
362
void die_path_inside_submodule(struct index_state *istate,
363
             const struct pathspec *ps)
364
7.32k
{
365
7.32k
  int i, j;
366
367
49.2k
  for (i = 0; i < istate->cache_nr; i++) {
368
41.8k
    struct cache_entry *ce = istate->cache[i];
369
41.8k
    int ce_len = ce_namelen(ce);
370
371
41.8k
    if (!S_ISGITLINK(ce->ce_mode))
372
41.8k
      continue;
373
374
0
    for (j = 0; j < ps->nr ; j++) {
375
0
      const struct pathspec_item *item = &ps->items[j];
376
377
0
      if (item->len <= ce_len)
378
0
        continue;
379
0
      if (item->match[ce_len] != '/')
380
0
        continue;
381
0
      if (strncmp(ce->name, item->match, ce_len))
382
0
        continue;
383
0
      if (item->len == ce_len + 1)
384
0
        continue;
385
386
0
      die(_("Pathspec '%s' is in submodule '%.*s'"),
387
0
          item->original, ce_len, ce->name);
388
0
    }
389
0
  }
390
7.32k
}
391
392
enum submodule_update_type parse_submodule_update_type(const char *value)
393
0
{
394
0
  if (!strcmp(value, "none"))
395
0
    return SM_UPDATE_NONE;
396
0
  else if (!strcmp(value, "checkout"))
397
0
    return SM_UPDATE_CHECKOUT;
398
0
  else if (!strcmp(value, "rebase"))
399
0
    return SM_UPDATE_REBASE;
400
0
  else if (!strcmp(value, "merge"))
401
0
    return SM_UPDATE_MERGE;
402
0
  else if (*value == '!')
403
0
    return SM_UPDATE_COMMAND;
404
0
  else
405
0
    return SM_UPDATE_UNSPECIFIED;
406
0
}
407
408
int parse_submodule_update_strategy(const char *value,
409
    struct submodule_update_strategy *dst)
410
0
{
411
0
  enum submodule_update_type type;
412
413
0
  free((void*)dst->command);
414
0
  dst->command = NULL;
415
416
0
  type = parse_submodule_update_type(value);
417
0
  if (type == SM_UPDATE_UNSPECIFIED)
418
0
    return -1;
419
420
0
  dst->type = type;
421
0
  if (type == SM_UPDATE_COMMAND)
422
0
    dst->command = xstrdup(value + 1);
423
424
0
  return 0;
425
0
}
426
427
const char *submodule_update_type_to_string(enum submodule_update_type type)
428
0
{
429
0
  switch (type) {
430
0
  case SM_UPDATE_CHECKOUT:
431
0
    return "checkout";
432
0
  case SM_UPDATE_MERGE:
433
0
    return "merge";
434
0
  case SM_UPDATE_REBASE:
435
0
    return "rebase";
436
0
  case SM_UPDATE_NONE:
437
0
    return "none";
438
0
  case SM_UPDATE_UNSPECIFIED:
439
0
  case SM_UPDATE_COMMAND:
440
0
    BUG("init_submodule() should handle type %d", type);
441
0
  default:
442
0
    BUG("unexpected update strategy type: %d", type);
443
0
  }
444
0
}
445
446
void handle_ignore_submodules_arg(struct diff_options *diffopt,
447
          const char *arg)
448
198
{
449
198
  diffopt->flags.ignore_submodule_set = 1;
450
198
  diffopt->flags.ignore_submodules = 0;
451
198
  diffopt->flags.ignore_untracked_in_submodules = 0;
452
198
  diffopt->flags.ignore_dirty_submodules = 0;
453
454
198
  if (!strcmp(arg, "all"))
455
0
    diffopt->flags.ignore_submodules = 1;
456
198
  else if (!strcmp(arg, "untracked"))
457
0
    diffopt->flags.ignore_untracked_in_submodules = 1;
458
198
  else if (!strcmp(arg, "dirty"))
459
99
    diffopt->flags.ignore_dirty_submodules = 1;
460
99
  else if (strcmp(arg, "none"))
461
0
    die(_("bad --ignore-submodules argument: %s"), arg);
462
  /*
463
   * Please update _git_status() in git-completion.bash when you
464
   * add new options
465
   */
466
198
}
467
468
static int prepare_submodule_diff_summary(struct repository *r, struct rev_info *rev,
469
            const char *path,
470
            struct commit *left, struct commit *right,
471
            struct commit_list *merge_bases)
472
0
{
473
0
  struct commit_list *list;
474
475
0
  repo_init_revisions(r, rev, NULL);
476
0
  setup_revisions(0, NULL, rev, NULL);
477
0
  rev->left_right = 1;
478
0
  rev->first_parent_only = 1;
479
0
  left->object.flags |= SYMMETRIC_LEFT;
480
0
  add_pending_object(rev, &left->object, path);
481
0
  add_pending_object(rev, &right->object, path);
482
0
  for (list = merge_bases; list; list = list->next) {
483
0
    list->item->object.flags |= UNINTERESTING;
484
0
    add_pending_object(rev, &list->item->object,
485
0
      oid_to_hex(&list->item->object.oid));
486
0
  }
487
0
  return prepare_revision_walk(rev);
488
0
}
489
490
static void print_submodule_diff_summary(struct repository *r, struct rev_info *rev, struct diff_options *o)
491
0
{
492
0
  static const char format[] = "  %m %s";
493
0
  struct strbuf sb = STRBUF_INIT;
494
0
  struct commit *commit;
495
496
0
  while ((commit = get_revision(rev))) {
497
0
    struct pretty_print_context ctx = {0};
498
0
    ctx.date_mode = rev->date_mode;
499
0
    ctx.output_encoding = get_log_output_encoding();
500
0
    strbuf_setlen(&sb, 0);
501
0
    repo_format_commit_message(r, commit, format, &sb,
502
0
              &ctx);
503
0
    strbuf_addch(&sb, '\n');
504
0
    if (commit->object.flags & SYMMETRIC_LEFT)
505
0
      diff_emit_submodule_del(o, sb.buf);
506
0
    else
507
0
      diff_emit_submodule_add(o, sb.buf);
508
0
  }
509
0
  strbuf_release(&sb);
510
0
}
511
512
void prepare_submodule_repo_env(struct strvec *out)
513
0
{
514
0
  prepare_other_repo_env(out, DEFAULT_GIT_DIR_ENVIRONMENT);
515
0
}
516
517
static void prepare_submodule_repo_env_in_gitdir(struct strvec *out)
518
0
{
519
0
  prepare_other_repo_env(out, ".");
520
0
}
521
522
/*
523
 * Initialize a repository struct for a submodule based on the provided 'path'.
524
 *
525
 * Returns the repository struct on success,
526
 * NULL when the submodule is not present.
527
 */
528
static struct repository *open_submodule(const char *path)
529
0
{
530
0
  struct strbuf sb = STRBUF_INIT;
531
0
  struct repository *out = xmalloc(sizeof(*out));
532
533
0
  if (submodule_to_gitdir(&sb, path) || repo_init(out, sb.buf, NULL)) {
534
0
    strbuf_release(&sb);
535
0
    free(out);
536
0
    return NULL;
537
0
  }
538
539
  /* Mark it as a submodule */
540
0
  out->submodule_prefix = xstrdup(path);
541
542
0
  strbuf_release(&sb);
543
0
  return out;
544
0
}
545
546
/*
547
 * Helper function to display the submodule header line prior to the full
548
 * summary output.
549
 *
550
 * If it can locate the submodule git directory it will create a repository
551
 * handle for the submodule and lookup both the left and right commits and
552
 * put them into the left and right pointers.
553
 */
554
static void show_submodule_header(struct diff_options *o,
555
    const char *path,
556
    struct object_id *one, struct object_id *two,
557
    unsigned dirty_submodule,
558
    struct repository *sub,
559
    struct commit **left, struct commit **right,
560
    struct commit_list **merge_bases)
561
0
{
562
0
  const char *message = NULL;
563
0
  struct strbuf sb = STRBUF_INIT;
564
0
  int fast_forward = 0, fast_backward = 0;
565
566
0
  if (dirty_submodule & DIRTY_SUBMODULE_UNTRACKED)
567
0
    diff_emit_submodule_untracked(o, path);
568
569
0
  if (dirty_submodule & DIRTY_SUBMODULE_MODIFIED)
570
0
    diff_emit_submodule_modified(o, path);
571
572
0
  if (is_null_oid(one))
573
0
    message = "(new submodule)";
574
0
  else if (is_null_oid(two))
575
0
    message = "(submodule deleted)";
576
577
0
  if (!sub) {
578
0
    if (!message)
579
0
      message = "(commits not present)";
580
0
    goto output_header;
581
0
  }
582
583
  /*
584
   * Attempt to lookup the commit references, and determine if this is
585
   * a fast forward or fast backwards update.
586
   */
587
0
  *left = lookup_commit_reference(sub, one);
588
0
  *right = lookup_commit_reference(sub, two);
589
590
  /*
591
   * Warn about missing commits in the submodule project, but only if
592
   * they aren't null.
593
   */
594
0
  if ((!is_null_oid(one) && !*left) ||
595
0
       (!is_null_oid(two) && !*right))
596
0
    message = "(commits not present)";
597
598
0
  *merge_bases = repo_get_merge_bases(sub, *left, *right);
599
0
  if (*merge_bases) {
600
0
    if ((*merge_bases)->item == *left)
601
0
      fast_forward = 1;
602
0
    else if ((*merge_bases)->item == *right)
603
0
      fast_backward = 1;
604
0
  }
605
606
0
  if (oideq(one, two)) {
607
0
    strbuf_release(&sb);
608
0
    return;
609
0
  }
610
611
0
output_header:
612
0
  strbuf_addf(&sb, "Submodule %s ", path);
613
0
  strbuf_add_unique_abbrev(&sb, one, DEFAULT_ABBREV);
614
0
  strbuf_addstr(&sb, (fast_backward || fast_forward) ? ".." : "...");
615
0
  strbuf_add_unique_abbrev(&sb, two, DEFAULT_ABBREV);
616
0
  if (message)
617
0
    strbuf_addf(&sb, " %s\n", message);
618
0
  else
619
0
    strbuf_addf(&sb, "%s:\n", fast_backward ? " (rewind)" : "");
620
0
  diff_emit_submodule_header(o, sb.buf);
621
622
0
  strbuf_release(&sb);
623
0
}
624
625
void show_submodule_diff_summary(struct diff_options *o, const char *path,
626
    struct object_id *one, struct object_id *two,
627
    unsigned dirty_submodule)
628
0
{
629
0
  struct rev_info rev = REV_INFO_INIT;
630
0
  struct commit *left = NULL, *right = NULL;
631
0
  struct commit_list *merge_bases = NULL;
632
0
  struct repository *sub;
633
634
0
  sub = open_submodule(path);
635
0
  show_submodule_header(o, path, one, two, dirty_submodule,
636
0
            sub, &left, &right, &merge_bases);
637
638
  /*
639
   * If we don't have both a left and a right pointer, there is no
640
   * reason to try and display a summary. The header line should contain
641
   * all the information the user needs.
642
   */
643
0
  if (!left || !right || !sub)
644
0
    goto out;
645
646
  /* Treat revision walker failure the same as missing commits */
647
0
  if (prepare_submodule_diff_summary(sub, &rev, path, left, right, merge_bases)) {
648
0
    diff_emit_submodule_error(o, "(revision walker failed)\n");
649
0
    goto out;
650
0
  }
651
652
0
  print_submodule_diff_summary(sub, &rev, o);
653
654
0
out:
655
0
  free_commit_list(merge_bases);
656
0
  release_revisions(&rev);
657
0
  clear_commit_marks(left, ~0);
658
0
  clear_commit_marks(right, ~0);
659
0
  if (sub) {
660
0
    repo_clear(sub);
661
0
    free(sub);
662
0
  }
663
0
}
664
665
void show_submodule_inline_diff(struct diff_options *o, const char *path,
666
    struct object_id *one, struct object_id *two,
667
    unsigned dirty_submodule)
668
0
{
669
0
  const struct object_id *old_oid = the_hash_algo->empty_tree, *new_oid = the_hash_algo->empty_tree;
670
0
  struct commit *left = NULL, *right = NULL;
671
0
  struct commit_list *merge_bases = NULL;
672
0
  struct child_process cp = CHILD_PROCESS_INIT;
673
0
  struct strbuf sb = STRBUF_INIT;
674
0
  struct repository *sub;
675
676
0
  sub = open_submodule(path);
677
0
  show_submodule_header(o, path, one, two, dirty_submodule,
678
0
            sub, &left, &right, &merge_bases);
679
680
  /* We need a valid left and right commit to display a difference */
681
0
  if (!(left || is_null_oid(one)) ||
682
0
      !(right || is_null_oid(two)))
683
0
    goto done;
684
685
0
  if (left)
686
0
    old_oid = one;
687
0
  if (right)
688
0
    new_oid = two;
689
690
0
  cp.git_cmd = 1;
691
0
  cp.dir = path;
692
0
  cp.out = -1;
693
0
  cp.no_stdin = 1;
694
695
  /* TODO: other options may need to be passed here. */
696
0
  strvec_pushl(&cp.args, "diff", "--submodule=diff", NULL);
697
0
  strvec_pushf(&cp.args, "--color=%s", want_color(o->use_color) ?
698
0
       "always" : "never");
699
700
0
  if (o->flags.reverse_diff) {
701
0
    strvec_pushf(&cp.args, "--src-prefix=%s%s/",
702
0
           o->b_prefix, path);
703
0
    strvec_pushf(&cp.args, "--dst-prefix=%s%s/",
704
0
           o->a_prefix, path);
705
0
  } else {
706
0
    strvec_pushf(&cp.args, "--src-prefix=%s%s/",
707
0
           o->a_prefix, path);
708
0
    strvec_pushf(&cp.args, "--dst-prefix=%s%s/",
709
0
           o->b_prefix, path);
710
0
  }
711
0
  strvec_push(&cp.args, oid_to_hex(old_oid));
712
  /*
713
   * If the submodule has modified content, we will diff against the
714
   * work tree, under the assumption that the user has asked for the
715
   * diff format and wishes to actually see all differences even if they
716
   * haven't yet been committed to the submodule yet.
717
   */
718
0
  if (!(dirty_submodule & DIRTY_SUBMODULE_MODIFIED))
719
0
    strvec_push(&cp.args, oid_to_hex(new_oid));
720
721
0
  prepare_submodule_repo_env(&cp.env);
722
723
0
  if (!is_directory(path)) {
724
    /* fall back to absorbed git dir, if any */
725
0
    if (!sub)
726
0
      goto done;
727
0
    cp.dir = sub->gitdir;
728
0
    strvec_push(&cp.env, GIT_DIR_ENVIRONMENT "=.");
729
0
    strvec_push(&cp.env, GIT_WORK_TREE_ENVIRONMENT "=.");
730
0
  }
731
732
0
  if (start_command(&cp)) {
733
0
    diff_emit_submodule_error(o, "(diff failed)\n");
734
0
    goto done;
735
0
  }
736
737
0
  while (strbuf_getwholeline_fd(&sb, cp.out, '\n') != EOF)
738
0
    diff_emit_submodule_pipethrough(o, sb.buf, sb.len);
739
740
0
  if (finish_command(&cp))
741
0
    diff_emit_submodule_error(o, "(diff failed)\n");
742
743
0
done:
744
0
  strbuf_release(&sb);
745
0
  free_commit_list(merge_bases);
746
0
  if (left)
747
0
    clear_commit_marks(left, ~0);
748
0
  if (right)
749
0
    clear_commit_marks(right, ~0);
750
0
  if (sub) {
751
0
    repo_clear(sub);
752
0
    free(sub);
753
0
  }
754
0
}
755
756
int should_update_submodules(void)
757
0
{
758
0
  return config_update_recurse_submodules == RECURSE_SUBMODULES_ON;
759
0
}
760
761
const struct submodule *submodule_from_ce(const struct cache_entry *ce)
762
0
{
763
0
  if (!S_ISGITLINK(ce->ce_mode))
764
0
    return NULL;
765
766
0
  if (!should_update_submodules())
767
0
    return NULL;
768
769
0
  return submodule_from_path(the_repository, null_oid(), ce->name);
770
0
}
771
772
773
struct collect_changed_submodules_cb_data {
774
  struct repository *repo;
775
  struct string_list *changed;
776
  const struct object_id *commit_oid;
777
};
778
779
/*
780
 * this would normally be two functions: default_name_from_path() and
781
 * path_from_default_name(). Since the default name is the same as
782
 * the submodule path we can get away with just one function which only
783
 * checks whether there is a submodule in the working directory at that
784
 * location.
785
 */
786
static const char *default_name_or_path(const char *path_or_name)
787
0
{
788
0
  int error_code;
789
790
0
  if (!is_submodule_populated_gently(path_or_name, &error_code))
791
0
    return NULL;
792
793
0
  return path_or_name;
794
0
}
795
796
/*
797
 * Holds relevant information for a changed submodule. Used as the .util
798
 * member of the changed submodule name string_list_item.
799
 *
800
 * (super_oid, path) allows the submodule config to be read from _some_
801
 * .gitmodules file. We store this information the first time we find a
802
 * superproject commit that points to the submodule, but this is
803
 * arbitrary - we can choose any (super_oid, path) that matches the
804
 * submodule's name.
805
 *
806
 * NEEDSWORK: Storing an arbitrary commit is undesirable because we can't
807
 * guarantee that we're reading the commit that the user would expect. A better
808
 * scheme would be to just fetch a submodule by its name. This requires two
809
 * steps:
810
 * - Create a function that behaves like repo_submodule_init(), but accepts a
811
 *   submodule name instead of treeish_name and path. This should be easy
812
 *   because repo_submodule_init() internally uses the submodule's name.
813
 *
814
 * - Replace most instances of 'struct submodule' (which is the .gitmodules
815
 *   config) with just the submodule name. This is OK because we expect
816
 *   submodule settings to be stored in .git/config (via "git submodule init"),
817
 *   not .gitmodules. This also lets us delete get_non_gitmodules_submodule(),
818
 *   which constructs a bogus 'struct submodule' for the sake of giving a
819
 *   placeholder name to a gitlink.
820
 */
821
struct changed_submodule_data {
822
  /*
823
   * The first superproject commit in the rev walk that points to
824
   * the submodule.
825
   */
826
  const struct object_id *super_oid;
827
  /*
828
   * Path to the submodule in the superproject commit referenced
829
   * by 'super_oid'.
830
   */
831
  char *path;
832
  /* The submodule commits that have changed in the rev walk. */
833
  struct oid_array new_commits;
834
};
835
836
static void changed_submodule_data_clear(struct changed_submodule_data *cs_data)
837
0
{
838
0
  oid_array_clear(&cs_data->new_commits);
839
0
  free(cs_data->path);
840
0
}
841
842
static void collect_changed_submodules_cb(struct diff_queue_struct *q,
843
            struct diff_options *options UNUSED,
844
            void *data)
845
0
{
846
0
  struct collect_changed_submodules_cb_data *me = data;
847
0
  struct string_list *changed = me->changed;
848
0
  const struct object_id *commit_oid = me->commit_oid;
849
0
  int i;
850
851
0
  for (i = 0; i < q->nr; i++) {
852
0
    struct diff_filepair *p = q->queue[i];
853
0
    const struct submodule *submodule;
854
0
    const char *name;
855
0
    struct string_list_item *item;
856
0
    struct changed_submodule_data *cs_data;
857
858
0
    if (!S_ISGITLINK(p->two->mode))
859
0
      continue;
860
861
0
    submodule = submodule_from_path(me->repo,
862
0
            commit_oid, p->two->path);
863
0
    if (submodule)
864
0
      name = submodule->name;
865
0
    else {
866
0
      name = default_name_or_path(p->two->path);
867
      /* make sure name does not collide with existing one */
868
0
      if (name)
869
0
        submodule = submodule_from_name(me->repo,
870
0
                commit_oid, name);
871
0
      if (submodule) {
872
0
        warning(_("Submodule in commit %s at path: "
873
0
          "'%s' collides with a submodule named "
874
0
          "the same. Skipping it."),
875
0
          oid_to_hex(commit_oid), p->two->path);
876
0
        name = NULL;
877
0
      }
878
0
    }
879
880
0
    if (!name)
881
0
      continue;
882
883
0
    item = string_list_insert(changed, name);
884
0
    if (item->util)
885
0
      cs_data = item->util;
886
0
    else {
887
0
      item->util = xcalloc(1, sizeof(struct changed_submodule_data));
888
0
      cs_data = item->util;
889
0
      cs_data->super_oid = commit_oid;
890
0
      cs_data->path = xstrdup(p->two->path);
891
0
    }
892
0
    oid_array_append(&cs_data->new_commits, &p->two->oid);
893
0
  }
894
0
}
895
896
/*
897
 * Collect the paths of submodules in 'changed' which have changed based on
898
 * the revisions as specified in 'argv'.  Each entry in 'changed' will also
899
 * have a corresponding 'struct oid_array' (in the 'util' field) which lists
900
 * what the submodule pointers were updated to during the change.
901
 */
902
static void collect_changed_submodules(struct repository *r,
903
               struct string_list *changed,
904
               struct strvec *argv)
905
0
{
906
0
  struct rev_info rev;
907
0
  const struct commit *commit;
908
0
  int save_warning;
909
0
  struct setup_revision_opt s_r_opt = {
910
0
    .assume_dashdash = 1,
911
0
  };
912
913
0
  save_warning = warn_on_object_refname_ambiguity;
914
0
  warn_on_object_refname_ambiguity = 0;
915
0
  repo_init_revisions(r, &rev, NULL);
916
0
  setup_revisions(argv->nr, argv->v, &rev, &s_r_opt);
917
0
  warn_on_object_refname_ambiguity = save_warning;
918
0
  if (prepare_revision_walk(&rev))
919
0
    die(_("revision walk setup failed"));
920
921
0
  while ((commit = get_revision(&rev))) {
922
0
    struct rev_info diff_rev;
923
0
    struct collect_changed_submodules_cb_data data;
924
0
    data.repo = r;
925
0
    data.changed = changed;
926
0
    data.commit_oid = &commit->object.oid;
927
928
0
    repo_init_revisions(r, &diff_rev, NULL);
929
0
    diff_rev.diffopt.output_format |= DIFF_FORMAT_CALLBACK;
930
0
    diff_rev.diffopt.format_callback = collect_changed_submodules_cb;
931
0
    diff_rev.diffopt.format_callback_data = &data;
932
0
    diff_rev.dense_combined_merges = 1;
933
0
    diff_tree_combined_merge(commit, &diff_rev);
934
0
    release_revisions(&diff_rev);
935
0
  }
936
937
0
  reset_revision_walk();
938
0
  release_revisions(&rev);
939
0
}
940
941
static void free_submodules_data(struct string_list *submodules)
942
0
{
943
0
  struct string_list_item *item;
944
0
  for_each_string_list_item(item, submodules)
945
0
    changed_submodule_data_clear(item->util);
946
947
0
  string_list_clear(submodules, 1);
948
0
}
949
950
static int has_remote(const char *refname UNUSED,
951
          const struct object_id *oid UNUSED,
952
          int flags UNUSED, void *cb_data UNUSED)
953
0
{
954
0
  return 1;
955
0
}
956
957
static int append_oid_to_argv(const struct object_id *oid, void *data)
958
0
{
959
0
  struct strvec *argv = data;
960
0
  strvec_push(argv, oid_to_hex(oid));
961
0
  return 0;
962
0
}
963
964
struct has_commit_data {
965
  struct repository *repo;
966
  int result;
967
  const char *path;
968
  const struct object_id *super_oid;
969
};
970
971
static int check_has_commit(const struct object_id *oid, void *data)
972
0
{
973
0
  struct has_commit_data *cb = data;
974
0
  struct repository subrepo;
975
0
  enum object_type type;
976
977
0
  if (repo_submodule_init(&subrepo, cb->repo, cb->path, cb->super_oid)) {
978
0
    cb->result = 0;
979
    /* subrepo failed to init, so don't clean it up. */
980
0
    return 0;
981
0
  }
982
983
0
  type = oid_object_info(&subrepo, oid, NULL);
984
985
0
  switch (type) {
986
0
  case OBJ_COMMIT:
987
0
    goto cleanup;
988
0
  case OBJ_BAD:
989
    /*
990
     * Object is missing or invalid. If invalid, an error message
991
     * has already been printed.
992
     */
993
0
    cb->result = 0;
994
0
    goto cleanup;
995
0
  default:
996
0
    die(_("submodule entry '%s' (%s) is a %s, not a commit"),
997
0
        cb->path, oid_to_hex(oid), type_name(type));
998
0
  }
999
0
cleanup:
1000
0
  repo_clear(&subrepo);
1001
0
  return 0;
1002
0
}
1003
1004
static int submodule_has_commits(struct repository *r,
1005
         const char *path,
1006
         const struct object_id *super_oid,
1007
         struct oid_array *commits)
1008
0
{
1009
0
  struct has_commit_data has_commit = {
1010
0
    .repo = r,
1011
0
    .result = 1,
1012
0
    .path = path,
1013
0
    .super_oid = super_oid
1014
0
  };
1015
1016
0
  oid_array_for_each_unique(commits, check_has_commit, &has_commit);
1017
1018
0
  if (has_commit.result) {
1019
    /*
1020
     * Even if the submodule is checked out and the commit is
1021
     * present, make sure it exists in the submodule's object store
1022
     * and that it is reachable from a ref.
1023
     */
1024
0
    struct child_process cp = CHILD_PROCESS_INIT;
1025
0
    struct strbuf out = STRBUF_INIT;
1026
1027
0
    strvec_pushl(&cp.args, "rev-list", "-n", "1", NULL);
1028
0
    oid_array_for_each_unique(commits, append_oid_to_argv, &cp.args);
1029
0
    strvec_pushl(&cp.args, "--not", "--all", NULL);
1030
1031
0
    prepare_submodule_repo_env(&cp.env);
1032
0
    cp.git_cmd = 1;
1033
0
    cp.no_stdin = 1;
1034
0
    cp.dir = path;
1035
1036
0
    if (capture_command(&cp, &out, GIT_MAX_HEXSZ + 1) || out.len)
1037
0
      has_commit.result = 0;
1038
1039
0
    strbuf_release(&out);
1040
0
  }
1041
1042
0
  return has_commit.result;
1043
0
}
1044
1045
static int submodule_needs_pushing(struct repository *r,
1046
           const char *path,
1047
           struct oid_array *commits)
1048
0
{
1049
0
  if (!submodule_has_commits(r, path, null_oid(), commits))
1050
    /*
1051
     * NOTE: We do consider it safe to return "no" here. The
1052
     * correct answer would be "We do not know" instead of
1053
     * "No push needed", but it is quite hard to change
1054
     * the submodule pointer without having the submodule
1055
     * around. If a user did however change the submodules
1056
     * without having the submodule around, this indicates
1057
     * an expert who knows what they are doing or a
1058
     * maintainer integrating work from other people. In
1059
     * both cases it should be safe to skip this check.
1060
     */
1061
0
    return 0;
1062
1063
0
  if (for_each_remote_ref_submodule(path, has_remote, NULL) > 0) {
1064
0
    struct child_process cp = CHILD_PROCESS_INIT;
1065
0
    struct strbuf buf = STRBUF_INIT;
1066
0
    int needs_pushing = 0;
1067
1068
0
    strvec_push(&cp.args, "rev-list");
1069
0
    oid_array_for_each_unique(commits, append_oid_to_argv, &cp.args);
1070
0
    strvec_pushl(&cp.args, "--not", "--remotes", "-n", "1" , NULL);
1071
1072
0
    prepare_submodule_repo_env(&cp.env);
1073
0
    cp.git_cmd = 1;
1074
0
    cp.no_stdin = 1;
1075
0
    cp.out = -1;
1076
0
    cp.dir = path;
1077
0
    if (start_command(&cp))
1078
0
      die(_("Could not run 'git rev-list <commits> --not --remotes -n 1' command in submodule %s"),
1079
0
          path);
1080
0
    if (strbuf_read(&buf, cp.out, the_hash_algo->hexsz + 1))
1081
0
      needs_pushing = 1;
1082
0
    finish_command(&cp);
1083
0
    close(cp.out);
1084
0
    strbuf_release(&buf);
1085
0
    return needs_pushing;
1086
0
  }
1087
1088
0
  return 0;
1089
0
}
1090
1091
int find_unpushed_submodules(struct repository *r,
1092
           struct oid_array *commits,
1093
           const char *remotes_name,
1094
           struct string_list *needs_pushing)
1095
0
{
1096
0
  struct string_list submodules = STRING_LIST_INIT_DUP;
1097
0
  struct string_list_item *name;
1098
0
  struct strvec argv = STRVEC_INIT;
1099
1100
  /* argv.v[0] will be ignored by setup_revisions */
1101
0
  strvec_push(&argv, "find_unpushed_submodules");
1102
0
  oid_array_for_each_unique(commits, append_oid_to_argv, &argv);
1103
0
  strvec_push(&argv, "--not");
1104
0
  strvec_pushf(&argv, "--remotes=%s", remotes_name);
1105
1106
0
  collect_changed_submodules(r, &submodules, &argv);
1107
1108
0
  for_each_string_list_item(name, &submodules) {
1109
0
    struct changed_submodule_data *cs_data = name->util;
1110
0
    const struct submodule *submodule;
1111
0
    const char *path = NULL;
1112
1113
0
    submodule = submodule_from_name(r, null_oid(), name->string);
1114
0
    if (submodule)
1115
0
      path = submodule->path;
1116
0
    else
1117
0
      path = default_name_or_path(name->string);
1118
1119
0
    if (!path)
1120
0
      continue;
1121
1122
0
    if (submodule_needs_pushing(r, path, &cs_data->new_commits))
1123
0
      string_list_insert(needs_pushing, path);
1124
0
  }
1125
1126
0
  free_submodules_data(&submodules);
1127
0
  strvec_clear(&argv);
1128
1129
0
  return needs_pushing->nr;
1130
0
}
1131
1132
static int push_submodule(const char *path,
1133
        const struct remote *remote,
1134
        const struct refspec *rs,
1135
        const struct string_list *push_options,
1136
        int dry_run)
1137
0
{
1138
0
  if (for_each_remote_ref_submodule(path, has_remote, NULL) > 0) {
1139
0
    struct child_process cp = CHILD_PROCESS_INIT;
1140
0
    strvec_push(&cp.args, "push");
1141
    /*
1142
     * When recursing into a submodule, treat any "only" configurations as "on-
1143
     * demand", since "only" would not work (we need all submodules to be pushed
1144
     * in order to be able to push the superproject).
1145
     */
1146
0
    strvec_push(&cp.args, "--recurse-submodules=only-is-on-demand");
1147
0
    if (dry_run)
1148
0
      strvec_push(&cp.args, "--dry-run");
1149
1150
0
    if (push_options && push_options->nr) {
1151
0
      const struct string_list_item *item;
1152
0
      for_each_string_list_item(item, push_options)
1153
0
        strvec_pushf(&cp.args, "--push-option=%s",
1154
0
               item->string);
1155
0
    }
1156
1157
0
    if (remote->origin != REMOTE_UNCONFIGURED) {
1158
0
      int i;
1159
0
      strvec_push(&cp.args, remote->name);
1160
0
      for (i = 0; i < rs->raw_nr; i++)
1161
0
        strvec_push(&cp.args, rs->raw[i]);
1162
0
    }
1163
1164
0
    prepare_submodule_repo_env(&cp.env);
1165
0
    cp.git_cmd = 1;
1166
0
    cp.no_stdin = 1;
1167
0
    cp.dir = path;
1168
0
    if (run_command(&cp))
1169
0
      return 0;
1170
0
    close(cp.out);
1171
0
  }
1172
1173
0
  return 1;
1174
0
}
1175
1176
/*
1177
 * Perform a check in the submodule to see if the remote and refspec work.
1178
 * Die if the submodule can't be pushed.
1179
 */
1180
static void submodule_push_check(const char *path, const char *head,
1181
         const struct remote *remote,
1182
         const struct refspec *rs)
1183
0
{
1184
0
  struct child_process cp = CHILD_PROCESS_INIT;
1185
0
  int i;
1186
1187
0
  strvec_push(&cp.args, "submodule--helper");
1188
0
  strvec_push(&cp.args, "push-check");
1189
0
  strvec_push(&cp.args, head);
1190
0
  strvec_push(&cp.args, remote->name);
1191
1192
0
  for (i = 0; i < rs->raw_nr; i++)
1193
0
    strvec_push(&cp.args, rs->raw[i]);
1194
1195
0
  prepare_submodule_repo_env(&cp.env);
1196
0
  cp.git_cmd = 1;
1197
0
  cp.no_stdin = 1;
1198
0
  cp.no_stdout = 1;
1199
0
  cp.dir = path;
1200
1201
  /*
1202
   * Simply indicate if 'submodule--helper push-check' failed.
1203
   * More detailed error information will be provided by the
1204
   * child process.
1205
   */
1206
0
  if (run_command(&cp))
1207
0
    die(_("process for submodule '%s' failed"), path);
1208
0
}
1209
1210
int push_unpushed_submodules(struct repository *r,
1211
           struct oid_array *commits,
1212
           const struct remote *remote,
1213
           const struct refspec *rs,
1214
           const struct string_list *push_options,
1215
           int dry_run)
1216
0
{
1217
0
  int i, ret = 1;
1218
0
  struct string_list needs_pushing = STRING_LIST_INIT_DUP;
1219
1220
0
  if (!find_unpushed_submodules(r, commits,
1221
0
              remote->name, &needs_pushing))
1222
0
    return 1;
1223
1224
  /*
1225
   * Verify that the remote and refspec can be propagated to all
1226
   * submodules.  This check can be skipped if the remote and refspec
1227
   * won't be propagated due to the remote being unconfigured (e.g. a URL
1228
   * instead of a remote name).
1229
   */
1230
0
  if (remote->origin != REMOTE_UNCONFIGURED) {
1231
0
    char *head;
1232
0
    struct object_id head_oid;
1233
1234
0
    head = resolve_refdup("HEAD", 0, &head_oid, NULL);
1235
0
    if (!head)
1236
0
      die(_("Failed to resolve HEAD as a valid ref."));
1237
1238
0
    for (i = 0; i < needs_pushing.nr; i++)
1239
0
      submodule_push_check(needs_pushing.items[i].string,
1240
0
               head, remote, rs);
1241
0
    free(head);
1242
0
  }
1243
1244
  /* Actually push the submodules */
1245
0
  for (i = 0; i < needs_pushing.nr; i++) {
1246
0
    const char *path = needs_pushing.items[i].string;
1247
0
    fprintf(stderr, _("Pushing submodule '%s'\n"), path);
1248
0
    if (!push_submodule(path, remote, rs,
1249
0
            push_options, dry_run)) {
1250
0
      fprintf(stderr, _("Unable to push submodule '%s'\n"), path);
1251
0
      ret = 0;
1252
0
    }
1253
0
  }
1254
1255
0
  string_list_clear(&needs_pushing, 0);
1256
1257
0
  return ret;
1258
0
}
1259
1260
static int append_oid_to_array(const char *ref UNUSED,
1261
             const struct object_id *oid,
1262
             int flags UNUSED, void *data)
1263
0
{
1264
0
  struct oid_array *array = data;
1265
0
  oid_array_append(array, oid);
1266
0
  return 0;
1267
0
}
1268
1269
void check_for_new_submodule_commits(struct object_id *oid)
1270
0
{
1271
0
  if (!initialized_fetch_ref_tips) {
1272
0
    for_each_ref(append_oid_to_array, &ref_tips_before_fetch);
1273
0
    initialized_fetch_ref_tips = 1;
1274
0
  }
1275
1276
0
  oid_array_append(&ref_tips_after_fetch, oid);
1277
0
}
1278
1279
/*
1280
 * Returns 1 if there is at least one submodule gitdir in
1281
 * $GIT_DIR/modules and 0 otherwise. This follows
1282
 * submodule_name_to_gitdir(), which looks for submodules in
1283
 * $GIT_DIR/modules, not $GIT_COMMON_DIR.
1284
 *
1285
 * A submodule can be moved to $GIT_DIR/modules manually by running "git
1286
 * submodule absorbgitdirs", or it may be initialized there by "git
1287
 * submodule update".
1288
 */
1289
static int repo_has_absorbed_submodules(struct repository *r)
1290
0
{
1291
0
  int ret;
1292
0
  struct strbuf buf = STRBUF_INIT;
1293
1294
0
  strbuf_repo_git_path(&buf, r, "modules/");
1295
0
  ret = file_exists(buf.buf) && !is_empty_dir(buf.buf);
1296
0
  strbuf_release(&buf);
1297
0
  return ret;
1298
0
}
1299
1300
static void calculate_changed_submodule_paths(struct repository *r,
1301
    struct string_list *changed_submodule_names)
1302
0
{
1303
0
  struct strvec argv = STRVEC_INIT;
1304
0
  struct string_list_item *name;
1305
1306
  /* No need to check if no submodules would be fetched */
1307
0
  if (!submodule_from_path(r, NULL, NULL) &&
1308
0
      !repo_has_absorbed_submodules(r))
1309
0
    return;
1310
1311
0
  strvec_push(&argv, "--"); /* argv[0] program name */
1312
0
  oid_array_for_each_unique(&ref_tips_after_fetch,
1313
0
           append_oid_to_argv, &argv);
1314
0
  strvec_push(&argv, "--not");
1315
0
  oid_array_for_each_unique(&ref_tips_before_fetch,
1316
0
           append_oid_to_argv, &argv);
1317
1318
  /*
1319
   * Collect all submodules (whether checked out or not) for which new
1320
   * commits have been recorded upstream in "changed_submodule_names".
1321
   */
1322
0
  collect_changed_submodules(r, changed_submodule_names, &argv);
1323
1324
0
  for_each_string_list_item(name, changed_submodule_names) {
1325
0
    struct changed_submodule_data *cs_data = name->util;
1326
0
    const struct submodule *submodule;
1327
0
    const char *path = NULL;
1328
1329
0
    submodule = submodule_from_name(r, null_oid(), name->string);
1330
0
    if (submodule)
1331
0
      path = submodule->path;
1332
0
    else
1333
0
      path = default_name_or_path(name->string);
1334
1335
0
    if (!path)
1336
0
      continue;
1337
1338
0
    if (submodule_has_commits(r, path, null_oid(), &cs_data->new_commits)) {
1339
0
      changed_submodule_data_clear(cs_data);
1340
0
      *name->string = '\0';
1341
0
    }
1342
0
  }
1343
1344
0
  string_list_remove_empty_items(changed_submodule_names, 1);
1345
1346
0
  strvec_clear(&argv);
1347
0
  oid_array_clear(&ref_tips_before_fetch);
1348
0
  oid_array_clear(&ref_tips_after_fetch);
1349
0
  initialized_fetch_ref_tips = 0;
1350
0
}
1351
1352
int submodule_touches_in_range(struct repository *r,
1353
             struct object_id *excl_oid,
1354
             struct object_id *incl_oid)
1355
0
{
1356
0
  struct string_list subs = STRING_LIST_INIT_DUP;
1357
0
  struct strvec args = STRVEC_INIT;
1358
0
  int ret;
1359
1360
  /* No need to check if there are no submodules configured */
1361
0
  if (!submodule_from_path(r, NULL, NULL))
1362
0
    return 0;
1363
1364
0
  strvec_push(&args, "--"); /* args[0] program name */
1365
0
  strvec_push(&args, oid_to_hex(incl_oid));
1366
0
  if (!is_null_oid(excl_oid)) {
1367
0
    strvec_push(&args, "--not");
1368
0
    strvec_push(&args, oid_to_hex(excl_oid));
1369
0
  }
1370
1371
0
  collect_changed_submodules(r, &subs, &args);
1372
0
  ret = subs.nr;
1373
1374
0
  strvec_clear(&args);
1375
1376
0
  free_submodules_data(&subs);
1377
0
  return ret;
1378
0
}
1379
1380
struct submodule_parallel_fetch {
1381
  /*
1382
   * The index of the last index entry processed by
1383
   * get_fetch_task_from_index().
1384
   */
1385
  int index_count;
1386
  /*
1387
   * The index of the last string_list entry processed by
1388
   * get_fetch_task_from_changed().
1389
   */
1390
  int changed_count;
1391
  struct strvec args;
1392
  struct repository *r;
1393
  const char *prefix;
1394
  int command_line_option;
1395
  int default_option;
1396
  int quiet;
1397
  int result;
1398
1399
  /*
1400
   * Names of submodules that have new commits. Generated by
1401
   * walking the newly fetched superproject commits.
1402
   */
1403
  struct string_list changed_submodule_names;
1404
  /*
1405
   * Names of submodules that have already been processed. Lets us
1406
   * avoid fetching the same submodule more than once.
1407
   */
1408
  struct string_list seen_submodule_names;
1409
1410
  /* Pending fetches by OIDs */
1411
  struct fetch_task **oid_fetch_tasks;
1412
  int oid_fetch_tasks_nr, oid_fetch_tasks_alloc;
1413
1414
  struct strbuf submodules_with_errors;
1415
};
1416
0
#define SPF_INIT { \
1417
0
  .args = STRVEC_INIT, \
1418
0
  .changed_submodule_names = STRING_LIST_INIT_DUP, \
1419
0
  .seen_submodule_names = STRING_LIST_INIT_DUP, \
1420
0
  .submodules_with_errors = STRBUF_INIT, \
1421
0
}
1422
1423
static int get_fetch_recurse_config(const struct submodule *submodule,
1424
            struct submodule_parallel_fetch *spf)
1425
0
{
1426
0
  if (spf->command_line_option != RECURSE_SUBMODULES_DEFAULT)
1427
0
    return spf->command_line_option;
1428
1429
0
  if (submodule) {
1430
0
    char *key;
1431
0
    const char *value;
1432
1433
0
    int fetch_recurse = submodule->fetch_recurse;
1434
0
    key = xstrfmt("submodule.%s.fetchRecurseSubmodules", submodule->name);
1435
0
    if (!repo_config_get_string_tmp(spf->r, key, &value)) {
1436
0
      fetch_recurse = parse_fetch_recurse_submodules_arg(key, value);
1437
0
    }
1438
0
    free(key);
1439
1440
0
    if (fetch_recurse != RECURSE_SUBMODULES_NONE)
1441
      /* local config overrules everything except commandline */
1442
0
      return fetch_recurse;
1443
0
  }
1444
1445
0
  return spf->default_option;
1446
0
}
1447
1448
/*
1449
 * Fetch in progress (if callback data) or
1450
 * pending (if in oid_fetch_tasks in struct submodule_parallel_fetch)
1451
 */
1452
struct fetch_task {
1453
  struct repository *repo;
1454
  const struct submodule *sub;
1455
  unsigned free_sub : 1; /* Do we need to free the submodule? */
1456
  const char *default_argv; /* The default fetch mode. */
1457
  struct strvec git_args; /* Args for the child git process. */
1458
1459
  struct oid_array *commits; /* Ensure these commits are fetched */
1460
};
1461
1462
/**
1463
 * When a submodule is not defined in .gitmodules, we cannot access it
1464
 * via the regular submodule-config. Create a fake submodule, which we can
1465
 * work on.
1466
 */
1467
static const struct submodule *get_non_gitmodules_submodule(const char *path)
1468
0
{
1469
0
  struct submodule *ret = NULL;
1470
0
  const char *name = default_name_or_path(path);
1471
1472
0
  if (!name)
1473
0
    return NULL;
1474
1475
0
  ret = xmalloc(sizeof(*ret));
1476
0
  memset(ret, 0, sizeof(*ret));
1477
0
  ret->path = name;
1478
0
  ret->name = name;
1479
1480
0
  return (const struct submodule *) ret;
1481
0
}
1482
1483
static void fetch_task_release(struct fetch_task *p)
1484
0
{
1485
0
  if (p->free_sub)
1486
0
    free((void*)p->sub);
1487
0
  p->free_sub = 0;
1488
0
  p->sub = NULL;
1489
1490
0
  if (p->repo)
1491
0
    repo_clear(p->repo);
1492
0
  FREE_AND_NULL(p->repo);
1493
1494
0
  strvec_clear(&p->git_args);
1495
0
}
1496
1497
static struct repository *get_submodule_repo_for(struct repository *r,
1498
             const char *path,
1499
             const struct object_id *treeish_name)
1500
0
{
1501
0
  struct repository *ret = xmalloc(sizeof(*ret));
1502
1503
0
  if (repo_submodule_init(ret, r, path, treeish_name)) {
1504
0
    free(ret);
1505
0
    return NULL;
1506
0
  }
1507
1508
0
  return ret;
1509
0
}
1510
1511
static struct fetch_task *fetch_task_create(struct submodule_parallel_fetch *spf,
1512
              const char *path,
1513
              const struct object_id *treeish_name)
1514
0
{
1515
0
  struct fetch_task *task = xmalloc(sizeof(*task));
1516
0
  memset(task, 0, sizeof(*task));
1517
1518
0
  task->sub = submodule_from_path(spf->r, treeish_name, path);
1519
1520
0
  if (!task->sub) {
1521
    /*
1522
     * No entry in .gitmodules? Technically not a submodule,
1523
     * but historically we supported repositories that happen to be
1524
     * in-place where a gitlink is. Keep supporting them.
1525
     */
1526
0
    task->sub = get_non_gitmodules_submodule(path);
1527
0
    if (!task->sub)
1528
0
      goto cleanup;
1529
1530
0
    task->free_sub = 1;
1531
0
  }
1532
1533
0
  if (string_list_lookup(&spf->seen_submodule_names, task->sub->name))
1534
0
    goto cleanup;
1535
1536
0
  switch (get_fetch_recurse_config(task->sub, spf))
1537
0
  {
1538
0
  default:
1539
0
  case RECURSE_SUBMODULES_DEFAULT:
1540
0
  case RECURSE_SUBMODULES_ON_DEMAND:
1541
0
    if (!task->sub ||
1542
0
      !string_list_lookup(
1543
0
        &spf->changed_submodule_names,
1544
0
        task->sub->name))
1545
0
      goto cleanup;
1546
0
    task->default_argv = "on-demand";
1547
0
    break;
1548
0
  case RECURSE_SUBMODULES_ON:
1549
0
    task->default_argv = "yes";
1550
0
    break;
1551
0
  case RECURSE_SUBMODULES_OFF:
1552
0
    goto cleanup;
1553
0
  }
1554
1555
0
  task->repo = get_submodule_repo_for(spf->r, path, treeish_name);
1556
1557
0
  return task;
1558
1559
0
 cleanup:
1560
0
  fetch_task_release(task);
1561
0
  free(task);
1562
0
  return NULL;
1563
0
}
1564
1565
static struct fetch_task *
1566
get_fetch_task_from_index(struct submodule_parallel_fetch *spf,
1567
        struct strbuf *err)
1568
0
{
1569
0
  for (; spf->index_count < spf->r->index->cache_nr; spf->index_count++) {
1570
0
    const struct cache_entry *ce =
1571
0
      spf->r->index->cache[spf->index_count];
1572
0
    struct fetch_task *task;
1573
1574
0
    if (!S_ISGITLINK(ce->ce_mode))
1575
0
      continue;
1576
1577
0
    task = fetch_task_create(spf, ce->name, null_oid());
1578
0
    if (!task)
1579
0
      continue;
1580
1581
0
    if (task->repo) {
1582
0
      if (!spf->quiet)
1583
0
        strbuf_addf(err, _("Fetching submodule %s%s\n"),
1584
0
              spf->prefix, ce->name);
1585
1586
0
      spf->index_count++;
1587
0
      return task;
1588
0
    } else {
1589
0
      struct strbuf empty_submodule_path = STRBUF_INIT;
1590
1591
0
      fetch_task_release(task);
1592
0
      free(task);
1593
1594
      /*
1595
       * An empty directory is normal,
1596
       * the submodule is not initialized
1597
       */
1598
0
      strbuf_addf(&empty_submodule_path, "%s/%s/",
1599
0
              spf->r->worktree,
1600
0
              ce->name);
1601
0
      if (S_ISGITLINK(ce->ce_mode) &&
1602
0
          !is_empty_dir(empty_submodule_path.buf)) {
1603
0
        spf->result = 1;
1604
0
        strbuf_addf(err,
1605
0
              _("Could not access submodule '%s'\n"),
1606
0
              ce->name);
1607
0
      }
1608
0
      strbuf_release(&empty_submodule_path);
1609
0
    }
1610
0
  }
1611
0
  return NULL;
1612
0
}
1613
1614
static struct fetch_task *
1615
get_fetch_task_from_changed(struct submodule_parallel_fetch *spf,
1616
          struct strbuf *err)
1617
0
{
1618
0
  for (; spf->changed_count < spf->changed_submodule_names.nr;
1619
0
       spf->changed_count++) {
1620
0
    struct string_list_item item =
1621
0
      spf->changed_submodule_names.items[spf->changed_count];
1622
0
    struct changed_submodule_data *cs_data = item.util;
1623
0
    struct fetch_task *task;
1624
1625
0
    if (!is_tree_submodule_active(spf->r, cs_data->super_oid,cs_data->path))
1626
0
      continue;
1627
1628
0
    task = fetch_task_create(spf, cs_data->path,
1629
0
           cs_data->super_oid);
1630
0
    if (!task)
1631
0
      continue;
1632
1633
0
    if (!task->repo) {
1634
0
      strbuf_addf(err, _("Could not access submodule '%s' at commit %s\n"),
1635
0
            cs_data->path,
1636
0
            repo_find_unique_abbrev(the_repository, cs_data->super_oid, DEFAULT_ABBREV));
1637
1638
0
      fetch_task_release(task);
1639
0
      free(task);
1640
0
      continue;
1641
0
    }
1642
1643
0
    if (!spf->quiet)
1644
0
      strbuf_addf(err,
1645
0
            _("Fetching submodule %s%s at commit %s\n"),
1646
0
            spf->prefix, task->sub->path,
1647
0
            repo_find_unique_abbrev(the_repository, cs_data->super_oid,
1648
0
                  DEFAULT_ABBREV));
1649
1650
0
    spf->changed_count++;
1651
    /*
1652
     * NEEDSWORK: Submodules set/unset a value for
1653
     * core.worktree when they are populated/unpopulated by
1654
     * "git checkout" (and similar commands, see
1655
     * submodule_move_head() and
1656
     * connect_work_tree_and_git_dir()), but if the
1657
     * submodule is unpopulated in another way (e.g. "git
1658
     * rm", "rm -r"), core.worktree will still be set even
1659
     * though the directory doesn't exist, and the child
1660
     * process will crash while trying to chdir into the
1661
     * nonexistent directory.
1662
     *
1663
     * In this case, we know that the submodule has no
1664
     * working tree, so we can work around this by
1665
     * setting "--work-tree=." (--bare does not work because
1666
     * worktree settings take precedence over bare-ness).
1667
     * However, this is not necessarily true in other cases,
1668
     * so a generalized solution is still necessary.
1669
     *
1670
     * Possible solutions:
1671
     * - teach "git [add|rm]" to unset core.worktree and
1672
     *   discourage users from removing submodules without
1673
     *   using a Git command.
1674
     * - teach submodule child processes to ignore stale
1675
     *   core.worktree values.
1676
     */
1677
0
    strvec_push(&task->git_args, "--work-tree=.");
1678
0
    return task;
1679
0
  }
1680
0
  return NULL;
1681
0
}
1682
1683
static int get_next_submodule(struct child_process *cp, struct strbuf *err,
1684
            void *data, void **task_cb)
1685
0
{
1686
0
  struct submodule_parallel_fetch *spf = data;
1687
0
  struct fetch_task *task =
1688
0
    get_fetch_task_from_index(spf, err);
1689
0
  if (!task)
1690
0
    task = get_fetch_task_from_changed(spf, err);
1691
1692
0
  if (task) {
1693
0
    struct strbuf submodule_prefix = STRBUF_INIT;
1694
1695
0
    child_process_init(cp);
1696
0
    cp->dir = task->repo->gitdir;
1697
0
    prepare_submodule_repo_env_in_gitdir(&cp->env);
1698
0
    cp->git_cmd = 1;
1699
0
    strvec_init(&cp->args);
1700
0
    if (task->git_args.nr)
1701
0
      strvec_pushv(&cp->args, task->git_args.v);
1702
0
    strvec_pushv(&cp->args, spf->args.v);
1703
0
    strvec_push(&cp->args, task->default_argv);
1704
0
    strvec_push(&cp->args, "--submodule-prefix");
1705
1706
0
    strbuf_addf(&submodule_prefix, "%s%s/",
1707
0
            spf->prefix,
1708
0
            task->sub->path);
1709
0
    strvec_push(&cp->args, submodule_prefix.buf);
1710
0
    *task_cb = task;
1711
1712
0
    strbuf_release(&submodule_prefix);
1713
0
    string_list_insert(&spf->seen_submodule_names, task->sub->name);
1714
0
    return 1;
1715
0
  }
1716
1717
0
  if (spf->oid_fetch_tasks_nr) {
1718
0
    struct fetch_task *task =
1719
0
      spf->oid_fetch_tasks[spf->oid_fetch_tasks_nr - 1];
1720
0
    struct strbuf submodule_prefix = STRBUF_INIT;
1721
0
    spf->oid_fetch_tasks_nr--;
1722
1723
0
    strbuf_addf(&submodule_prefix, "%s%s/",
1724
0
          spf->prefix, task->sub->path);
1725
1726
0
    child_process_init(cp);
1727
0
    prepare_submodule_repo_env_in_gitdir(&cp->env);
1728
0
    cp->git_cmd = 1;
1729
0
    cp->dir = task->repo->gitdir;
1730
1731
0
    strvec_init(&cp->args);
1732
0
    strvec_pushv(&cp->args, spf->args.v);
1733
0
    strvec_push(&cp->args, "on-demand");
1734
0
    strvec_push(&cp->args, "--submodule-prefix");
1735
0
    strvec_push(&cp->args, submodule_prefix.buf);
1736
1737
    /* NEEDSWORK: have get_default_remote from submodule--helper */
1738
0
    strvec_push(&cp->args, "origin");
1739
0
    oid_array_for_each_unique(task->commits,
1740
0
            append_oid_to_argv, &cp->args);
1741
1742
0
    *task_cb = task;
1743
0
    strbuf_release(&submodule_prefix);
1744
0
    return 1;
1745
0
  }
1746
1747
0
  return 0;
1748
0
}
1749
1750
static int fetch_start_failure(struct strbuf *err UNUSED,
1751
             void *cb, void *task_cb)
1752
0
{
1753
0
  struct submodule_parallel_fetch *spf = cb;
1754
0
  struct fetch_task *task = task_cb;
1755
1756
0
  spf->result = 1;
1757
1758
0
  fetch_task_release(task);
1759
0
  return 0;
1760
0
}
1761
1762
static int commit_missing_in_sub(const struct object_id *oid, void *data)
1763
0
{
1764
0
  struct repository *subrepo = data;
1765
1766
0
  enum object_type type = oid_object_info(subrepo, oid, NULL);
1767
1768
0
  return type != OBJ_COMMIT;
1769
0
}
1770
1771
static int fetch_finish(int retvalue, struct strbuf *err UNUSED,
1772
      void *cb, void *task_cb)
1773
0
{
1774
0
  struct submodule_parallel_fetch *spf = cb;
1775
0
  struct fetch_task *task = task_cb;
1776
1777
0
  struct string_list_item *it;
1778
0
  struct changed_submodule_data *cs_data;
1779
1780
0
  if (!task || !task->sub)
1781
0
    BUG("callback cookie bogus");
1782
1783
0
  if (retvalue) {
1784
    /*
1785
     * NEEDSWORK: This indicates that the overall fetch
1786
     * failed, even though there may be a subsequent fetch
1787
     * by commit hash that might work. It may be a good
1788
     * idea to not indicate failure in this case, and only
1789
     * indicate failure if the subsequent fetch fails.
1790
     */
1791
0
    spf->result = 1;
1792
1793
0
    strbuf_addf(&spf->submodules_with_errors, "\t%s\n",
1794
0
          task->sub->name);
1795
0
  }
1796
1797
  /* Is this the second time we process this submodule? */
1798
0
  if (task->commits)
1799
0
    goto out;
1800
1801
0
  it = string_list_lookup(&spf->changed_submodule_names, task->sub->name);
1802
0
  if (!it)
1803
    /* Could be an unchanged submodule, not contained in the list */
1804
0
    goto out;
1805
1806
0
  cs_data = it->util;
1807
0
  oid_array_filter(&cs_data->new_commits,
1808
0
       commit_missing_in_sub,
1809
0
       task->repo);
1810
1811
  /* Are there commits we want, but do not exist? */
1812
0
  if (cs_data->new_commits.nr) {
1813
0
    task->commits = &cs_data->new_commits;
1814
0
    ALLOC_GROW(spf->oid_fetch_tasks,
1815
0
         spf->oid_fetch_tasks_nr + 1,
1816
0
         spf->oid_fetch_tasks_alloc);
1817
0
    spf->oid_fetch_tasks[spf->oid_fetch_tasks_nr] = task;
1818
0
    spf->oid_fetch_tasks_nr++;
1819
0
    return 0;
1820
0
  }
1821
1822
0
out:
1823
0
  fetch_task_release(task);
1824
1825
0
  return 0;
1826
0
}
1827
1828
int fetch_submodules(struct repository *r,
1829
         const struct strvec *options,
1830
         const char *prefix, int command_line_option,
1831
         int default_option,
1832
         int quiet, int max_parallel_jobs)
1833
0
{
1834
0
  int i;
1835
0
  struct submodule_parallel_fetch spf = SPF_INIT;
1836
0
  const struct run_process_parallel_opts opts = {
1837
0
    .tr2_category = "submodule",
1838
0
    .tr2_label = "parallel/fetch",
1839
1840
0
    .processes = max_parallel_jobs,
1841
1842
0
    .get_next_task = get_next_submodule,
1843
0
    .start_failure = fetch_start_failure,
1844
0
    .task_finished = fetch_finish,
1845
0
    .data = &spf,
1846
0
  };
1847
1848
0
  spf.r = r;
1849
0
  spf.command_line_option = command_line_option;
1850
0
  spf.default_option = default_option;
1851
0
  spf.quiet = quiet;
1852
0
  spf.prefix = prefix;
1853
1854
0
  if (!r->worktree)
1855
0
    goto out;
1856
1857
0
  if (repo_read_index(r) < 0)
1858
0
    die(_("index file corrupt"));
1859
1860
0
  strvec_push(&spf.args, "fetch");
1861
0
  for (i = 0; i < options->nr; i++)
1862
0
    strvec_push(&spf.args, options->v[i]);
1863
0
  strvec_push(&spf.args, "--recurse-submodules-default");
1864
  /* default value, "--submodule-prefix" and its value are added later */
1865
1866
0
  calculate_changed_submodule_paths(r, &spf.changed_submodule_names);
1867
0
  string_list_sort(&spf.changed_submodule_names);
1868
0
  run_processes_parallel(&opts);
1869
1870
0
  if (spf.submodules_with_errors.len > 0)
1871
0
    fprintf(stderr, _("Errors during submodule fetch:\n%s"),
1872
0
      spf.submodules_with_errors.buf);
1873
1874
1875
0
  strvec_clear(&spf.args);
1876
0
out:
1877
0
  free_submodules_data(&spf.changed_submodule_names);
1878
0
  return spf.result;
1879
0
}
1880
1881
unsigned is_submodule_modified(const char *path, int ignore_untracked)
1882
0
{
1883
0
  struct child_process cp = CHILD_PROCESS_INIT;
1884
0
  struct strbuf buf = STRBUF_INIT;
1885
0
  FILE *fp;
1886
0
  unsigned dirty_submodule = 0;
1887
0
  const char *git_dir;
1888
0
  int ignore_cp_exit_code = 0;
1889
1890
0
  strbuf_addf(&buf, "%s/.git", path);
1891
0
  git_dir = read_gitfile(buf.buf);
1892
0
  if (!git_dir)
1893
0
    git_dir = buf.buf;
1894
0
  if (!is_git_directory(git_dir)) {
1895
0
    if (is_directory(git_dir))
1896
0
      die(_("'%s' not recognized as a git repository"), git_dir);
1897
0
    strbuf_release(&buf);
1898
    /* The submodule is not checked out, so it is not modified */
1899
0
    return 0;
1900
0
  }
1901
0
  strbuf_reset(&buf);
1902
1903
0
  strvec_pushl(&cp.args, "status", "--porcelain=2", NULL);
1904
0
  if (ignore_untracked)
1905
0
    strvec_push(&cp.args, "-uno");
1906
1907
0
  prepare_submodule_repo_env(&cp.env);
1908
0
  cp.git_cmd = 1;
1909
0
  cp.no_stdin = 1;
1910
0
  cp.out = -1;
1911
0
  cp.dir = path;
1912
0
  if (start_command(&cp))
1913
0
    die(_("Could not run 'git status --porcelain=2' in submodule %s"), path);
1914
1915
0
  fp = xfdopen(cp.out, "r");
1916
0
  while (strbuf_getwholeline(&buf, fp, '\n') != EOF) {
1917
    /* regular untracked files */
1918
0
    if (buf.buf[0] == '?')
1919
0
      dirty_submodule |= DIRTY_SUBMODULE_UNTRACKED;
1920
1921
0
    if (buf.buf[0] == 'u' ||
1922
0
        buf.buf[0] == '1' ||
1923
0
        buf.buf[0] == '2') {
1924
      /* T = line type, XY = status, SSSS = submodule state */
1925
0
      if (buf.len < strlen("T XY SSSS"))
1926
0
        BUG("invalid status --porcelain=2 line %s",
1927
0
            buf.buf);
1928
1929
0
      if (buf.buf[5] == 'S' && buf.buf[8] == 'U')
1930
        /* nested untracked file */
1931
0
        dirty_submodule |= DIRTY_SUBMODULE_UNTRACKED;
1932
1933
0
      if (buf.buf[0] == 'u' ||
1934
0
          buf.buf[0] == '2' ||
1935
0
          memcmp(buf.buf + 5, "S..U", 4))
1936
        /* other change */
1937
0
        dirty_submodule |= DIRTY_SUBMODULE_MODIFIED;
1938
0
    }
1939
1940
0
    if ((dirty_submodule & DIRTY_SUBMODULE_MODIFIED) &&
1941
0
        ((dirty_submodule & DIRTY_SUBMODULE_UNTRACKED) ||
1942
0
         ignore_untracked)) {
1943
      /*
1944
       * We're not interested in any further information from
1945
       * the child any more, neither output nor its exit code.
1946
       */
1947
0
      ignore_cp_exit_code = 1;
1948
0
      break;
1949
0
    }
1950
0
  }
1951
0
  fclose(fp);
1952
1953
0
  if (finish_command(&cp) && !ignore_cp_exit_code)
1954
0
    die(_("'git status --porcelain=2' failed in submodule %s"), path);
1955
1956
0
  strbuf_release(&buf);
1957
0
  return dirty_submodule;
1958
0
}
1959
1960
int submodule_uses_gitfile(const char *path)
1961
0
{
1962
0
  struct child_process cp = CHILD_PROCESS_INIT;
1963
0
  struct strbuf buf = STRBUF_INIT;
1964
0
  const char *git_dir;
1965
1966
0
  strbuf_addf(&buf, "%s/.git", path);
1967
0
  git_dir = read_gitfile(buf.buf);
1968
0
  if (!git_dir) {
1969
0
    strbuf_release(&buf);
1970
0
    return 0;
1971
0
  }
1972
0
  strbuf_release(&buf);
1973
1974
  /* Now test that all nested submodules use a gitfile too */
1975
0
  strvec_pushl(&cp.args,
1976
0
         "submodule", "foreach", "--quiet", "--recursive",
1977
0
         "test -f .git", NULL);
1978
1979
0
  prepare_submodule_repo_env(&cp.env);
1980
0
  cp.git_cmd = 1;
1981
0
  cp.no_stdin = 1;
1982
0
  cp.no_stderr = 1;
1983
0
  cp.no_stdout = 1;
1984
0
  cp.dir = path;
1985
0
  if (run_command(&cp))
1986
0
    return 0;
1987
1988
0
  return 1;
1989
0
}
1990
1991
/*
1992
 * Check if it is a bad idea to remove a submodule, i.e. if we'd lose data
1993
 * when doing so.
1994
 *
1995
 * Return 1 if we'd lose data, return 0 if the removal is fine,
1996
 * and negative values for errors.
1997
 */
1998
int bad_to_remove_submodule(const char *path, unsigned flags)
1999
0
{
2000
0
  ssize_t len;
2001
0
  struct child_process cp = CHILD_PROCESS_INIT;
2002
0
  struct strbuf buf = STRBUF_INIT;
2003
0
  int ret = 0;
2004
2005
0
  if (!file_exists(path) || is_empty_dir(path))
2006
0
    return 0;
2007
2008
0
  if (!submodule_uses_gitfile(path))
2009
0
    return 1;
2010
2011
0
  strvec_pushl(&cp.args, "status", "--porcelain",
2012
0
         "--ignore-submodules=none", NULL);
2013
2014
0
  if (flags & SUBMODULE_REMOVAL_IGNORE_UNTRACKED)
2015
0
    strvec_push(&cp.args, "-uno");
2016
0
  else
2017
0
    strvec_push(&cp.args, "-uall");
2018
2019
0
  if (!(flags & SUBMODULE_REMOVAL_IGNORE_IGNORED_UNTRACKED))
2020
0
    strvec_push(&cp.args, "--ignored");
2021
2022
0
  prepare_submodule_repo_env(&cp.env);
2023
0
  cp.git_cmd = 1;
2024
0
  cp.no_stdin = 1;
2025
0
  cp.out = -1;
2026
0
  cp.dir = path;
2027
0
  if (start_command(&cp)) {
2028
0
    if (flags & SUBMODULE_REMOVAL_DIE_ON_ERROR)
2029
0
      die(_("could not start 'git status' in submodule '%s'"),
2030
0
        path);
2031
0
    ret = -1;
2032
0
    goto out;
2033
0
  }
2034
2035
0
  len = strbuf_read(&buf, cp.out, 1024);
2036
0
  if (len > 2)
2037
0
    ret = 1;
2038
0
  close(cp.out);
2039
2040
0
  if (finish_command(&cp)) {
2041
0
    if (flags & SUBMODULE_REMOVAL_DIE_ON_ERROR)
2042
0
      die(_("could not run 'git status' in submodule '%s'"),
2043
0
        path);
2044
0
    ret = -1;
2045
0
  }
2046
0
out:
2047
0
  strbuf_release(&buf);
2048
0
  return ret;
2049
0
}
2050
2051
void submodule_unset_core_worktree(const struct submodule *sub)
2052
0
{
2053
0
  struct strbuf config_path = STRBUF_INIT;
2054
2055
0
  submodule_name_to_gitdir(&config_path, the_repository, sub->name);
2056
0
  strbuf_addstr(&config_path, "/config");
2057
2058
0
  if (git_config_set_in_file_gently(config_path.buf, "core.worktree", NULL))
2059
0
    warning(_("Could not unset core.worktree setting in submodule '%s'"),
2060
0
        sub->path);
2061
2062
0
  strbuf_release(&config_path);
2063
0
}
2064
2065
static int submodule_has_dirty_index(const struct submodule *sub)
2066
0
{
2067
0
  struct child_process cp = CHILD_PROCESS_INIT;
2068
2069
0
  prepare_submodule_repo_env(&cp.env);
2070
2071
0
  cp.git_cmd = 1;
2072
0
  strvec_pushl(&cp.args, "diff-index", "--quiet",
2073
0
         "--cached", "HEAD", NULL);
2074
0
  cp.no_stdin = 1;
2075
0
  cp.no_stdout = 1;
2076
0
  cp.dir = sub->path;
2077
0
  if (start_command(&cp))
2078
0
    die(_("could not recurse into submodule '%s'"), sub->path);
2079
2080
0
  return finish_command(&cp);
2081
0
}
2082
2083
static void submodule_reset_index(const char *path, const char *super_prefix)
2084
0
{
2085
0
  struct child_process cp = CHILD_PROCESS_INIT;
2086
0
  prepare_submodule_repo_env(&cp.env);
2087
2088
0
  cp.git_cmd = 1;
2089
0
  cp.no_stdin = 1;
2090
0
  cp.dir = path;
2091
2092
  /* TODO: determine if this might overwright untracked files */
2093
0
  strvec_pushl(&cp.args, "read-tree", "-u", "--reset", NULL);
2094
0
  strvec_pushf(&cp.args, "--super-prefix=%s%s/",
2095
0
         (super_prefix ? super_prefix : ""), path);
2096
2097
0
  strvec_push(&cp.args, empty_tree_oid_hex());
2098
2099
0
  if (run_command(&cp))
2100
0
    die(_("could not reset submodule index"));
2101
0
}
2102
2103
/**
2104
 * Moves a submodule at a given path from a given head to another new head.
2105
 * For edge cases (a submodule coming into existence or removing a submodule)
2106
 * pass NULL for old or new respectively.
2107
 */
2108
int submodule_move_head(const char *path, const char *super_prefix,
2109
      const char *old_head, const char *new_head,
2110
      unsigned flags)
2111
0
{
2112
0
  int ret = 0;
2113
0
  struct child_process cp = CHILD_PROCESS_INIT;
2114
0
  const struct submodule *sub;
2115
0
  int *error_code_ptr, error_code;
2116
2117
0
  if (!is_submodule_active(the_repository, path))
2118
0
    return 0;
2119
2120
0
  if (flags & SUBMODULE_MOVE_HEAD_FORCE)
2121
    /*
2122
     * Pass non NULL pointer to is_submodule_populated_gently
2123
     * to prevent die()-ing. We'll use connect_work_tree_and_git_dir
2124
     * to fixup the submodule in the force case later.
2125
     */
2126
0
    error_code_ptr = &error_code;
2127
0
  else
2128
0
    error_code_ptr = NULL;
2129
2130
0
  if (old_head && !is_submodule_populated_gently(path, error_code_ptr))
2131
0
    return 0;
2132
2133
0
  sub = submodule_from_path(the_repository, null_oid(), path);
2134
2135
0
  if (!sub)
2136
0
    BUG("could not get submodule information for '%s'", path);
2137
2138
0
  if (old_head && !(flags & SUBMODULE_MOVE_HEAD_FORCE)) {
2139
    /* Check if the submodule has a dirty index. */
2140
0
    if (submodule_has_dirty_index(sub))
2141
0
      return error(_("submodule '%s' has dirty index"), path);
2142
0
  }
2143
2144
0
  if (!(flags & SUBMODULE_MOVE_HEAD_DRY_RUN)) {
2145
0
    if (old_head) {
2146
0
      if (!submodule_uses_gitfile(path))
2147
0
        absorb_git_dir_into_superproject(path,
2148
0
                 super_prefix);
2149
0
    } else {
2150
0
      struct strbuf gitdir = STRBUF_INIT;
2151
0
      submodule_name_to_gitdir(&gitdir, the_repository,
2152
0
             sub->name);
2153
0
      connect_work_tree_and_git_dir(path, gitdir.buf, 0);
2154
0
      strbuf_release(&gitdir);
2155
2156
      /* make sure the index is clean as well */
2157
0
      submodule_reset_index(path, super_prefix);
2158
0
    }
2159
2160
0
    if (old_head && (flags & SUBMODULE_MOVE_HEAD_FORCE)) {
2161
0
      struct strbuf gitdir = STRBUF_INIT;
2162
0
      submodule_name_to_gitdir(&gitdir, the_repository,
2163
0
             sub->name);
2164
0
      connect_work_tree_and_git_dir(path, gitdir.buf, 1);
2165
0
      strbuf_release(&gitdir);
2166
0
    }
2167
0
  }
2168
2169
0
  prepare_submodule_repo_env(&cp.env);
2170
2171
0
  cp.git_cmd = 1;
2172
0
  cp.no_stdin = 1;
2173
0
  cp.dir = path;
2174
2175
0
  strvec_pushl(&cp.args, "read-tree", "--recurse-submodules", NULL);
2176
0
  strvec_pushf(&cp.args, "--super-prefix=%s%s/",
2177
0
         (super_prefix ? super_prefix : ""), path);
2178
2179
0
  if (flags & SUBMODULE_MOVE_HEAD_DRY_RUN)
2180
0
    strvec_push(&cp.args, "-n");
2181
0
  else
2182
0
    strvec_push(&cp.args, "-u");
2183
2184
0
  if (flags & SUBMODULE_MOVE_HEAD_FORCE)
2185
0
    strvec_push(&cp.args, "--reset");
2186
0
  else
2187
0
    strvec_push(&cp.args, "-m");
2188
2189
0
  if (!(flags & SUBMODULE_MOVE_HEAD_FORCE))
2190
0
    strvec_push(&cp.args, old_head ? old_head : empty_tree_oid_hex());
2191
2192
0
  strvec_push(&cp.args, new_head ? new_head : empty_tree_oid_hex());
2193
2194
0
  if (run_command(&cp)) {
2195
0
    ret = error(_("Submodule '%s' could not be updated."), path);
2196
0
    goto out;
2197
0
  }
2198
2199
0
  if (!(flags & SUBMODULE_MOVE_HEAD_DRY_RUN)) {
2200
0
    if (new_head) {
2201
0
      child_process_init(&cp);
2202
      /* also set the HEAD accordingly */
2203
0
      cp.git_cmd = 1;
2204
0
      cp.no_stdin = 1;
2205
0
      cp.dir = path;
2206
2207
0
      prepare_submodule_repo_env(&cp.env);
2208
0
      strvec_pushl(&cp.args, "update-ref", "HEAD",
2209
0
             "--no-deref", new_head, NULL);
2210
2211
0
      if (run_command(&cp)) {
2212
0
        ret = -1;
2213
0
        goto out;
2214
0
      }
2215
0
    } else {
2216
0
      struct strbuf sb = STRBUF_INIT;
2217
2218
0
      strbuf_addf(&sb, "%s/.git", path);
2219
0
      unlink_or_warn(sb.buf);
2220
0
      strbuf_release(&sb);
2221
2222
0
      if (is_empty_dir(path))
2223
0
        rmdir_or_warn(path);
2224
2225
0
      submodule_unset_core_worktree(sub);
2226
0
    }
2227
0
  }
2228
0
out:
2229
0
  return ret;
2230
0
}
2231
2232
int validate_submodule_git_dir(char *git_dir, const char *submodule_name)
2233
0
{
2234
0
  size_t len = strlen(git_dir), suffix_len = strlen(submodule_name);
2235
0
  char *p;
2236
0
  int ret = 0;
2237
2238
0
  if (len <= suffix_len || (p = git_dir + len - suffix_len)[-1] != '/' ||
2239
0
      strcmp(p, submodule_name))
2240
0
    BUG("submodule name '%s' not a suffix of git dir '%s'",
2241
0
        submodule_name, git_dir);
2242
2243
  /*
2244
   * We prevent the contents of sibling submodules' git directories to
2245
   * clash.
2246
   *
2247
   * Example: having a submodule named `hippo` and another one named
2248
   * `hippo/hooks` would result in the git directories
2249
   * `.git/modules/hippo/` and `.git/modules/hippo/hooks/`, respectively,
2250
   * but the latter directory is already designated to contain the hooks
2251
   * of the former.
2252
   */
2253
0
  for (; *p; p++) {
2254
0
    if (is_dir_sep(*p)) {
2255
0
      char c = *p;
2256
2257
0
      *p = '\0';
2258
0
      if (is_git_directory(git_dir))
2259
0
        ret = -1;
2260
0
      *p = c;
2261
2262
0
      if (ret < 0)
2263
0
        return error(_("submodule git dir '%s' is "
2264
0
                 "inside git dir '%.*s'"),
2265
0
               git_dir,
2266
0
               (int)(p - git_dir), git_dir);
2267
0
    }
2268
0
  }
2269
2270
0
  return 0;
2271
0
}
2272
2273
/*
2274
 * Embeds a single submodules git directory into the superprojects git dir,
2275
 * non recursively.
2276
 */
2277
static void relocate_single_git_dir_into_superproject(const char *path,
2278
                  const char *super_prefix)
2279
0
{
2280
0
  char *old_git_dir = NULL, *real_old_git_dir = NULL, *real_new_git_dir = NULL;
2281
0
  struct strbuf new_gitdir = STRBUF_INIT;
2282
0
  const struct submodule *sub;
2283
2284
0
  if (submodule_uses_worktrees(path))
2285
0
    die(_("relocate_gitdir for submodule '%s' with "
2286
0
          "more than one worktree not supported"), path);
2287
2288
0
  old_git_dir = xstrfmt("%s/.git", path);
2289
0
  if (read_gitfile(old_git_dir))
2290
    /* If it is an actual gitfile, it doesn't need migration. */
2291
0
    return;
2292
2293
0
  real_old_git_dir = real_pathdup(old_git_dir, 1);
2294
2295
0
  sub = submodule_from_path(the_repository, null_oid(), path);
2296
0
  if (!sub)
2297
0
    die(_("could not lookup name for submodule '%s'"), path);
2298
2299
0
  submodule_name_to_gitdir(&new_gitdir, the_repository, sub->name);
2300
0
  if (validate_submodule_git_dir(new_gitdir.buf, sub->name) < 0)
2301
0
    die(_("refusing to move '%s' into an existing git dir"),
2302
0
        real_old_git_dir);
2303
0
  if (safe_create_leading_directories_const(new_gitdir.buf) < 0)
2304
0
    die(_("could not create directory '%s'"), new_gitdir.buf);
2305
0
  real_new_git_dir = real_pathdup(new_gitdir.buf, 1);
2306
2307
0
  fprintf(stderr, _("Migrating git directory of '%s%s' from\n'%s' to\n'%s'\n"),
2308
0
    super_prefix ? super_prefix : "", path,
2309
0
    real_old_git_dir, real_new_git_dir);
2310
2311
0
  relocate_gitdir(path, real_old_git_dir, real_new_git_dir);
2312
2313
0
  free(old_git_dir);
2314
0
  free(real_old_git_dir);
2315
0
  free(real_new_git_dir);
2316
0
  strbuf_release(&new_gitdir);
2317
0
}
2318
2319
static void absorb_git_dir_into_superproject_recurse(const char *path,
2320
                 const char *super_prefix)
2321
0
{
2322
2323
0
  struct child_process cp = CHILD_PROCESS_INIT;
2324
2325
0
  cp.dir = path;
2326
0
  cp.git_cmd = 1;
2327
0
  cp.no_stdin = 1;
2328
0
  strvec_pushl(&cp.args, "submodule--helper",
2329
0
         "absorbgitdirs", NULL);
2330
0
  strvec_pushf(&cp.args, "--super-prefix=%s%s/", super_prefix ?
2331
0
         super_prefix : "", path);
2332
2333
0
  prepare_submodule_repo_env(&cp.env);
2334
0
  if (run_command(&cp))
2335
0
    die(_("could not recurse into submodule '%s'"), path);
2336
0
}
2337
2338
/*
2339
 * Migrate the git directory of the submodule given by path from
2340
 * having its git directory within the working tree to the git dir nested
2341
 * in its superprojects git dir under modules/.
2342
 */
2343
void absorb_git_dir_into_superproject(const char *path,
2344
              const char *super_prefix)
2345
0
{
2346
0
  int err_code;
2347
0
  const char *sub_git_dir;
2348
0
  struct strbuf gitdir = STRBUF_INIT;
2349
0
  strbuf_addf(&gitdir, "%s/.git", path);
2350
0
  sub_git_dir = resolve_gitdir_gently(gitdir.buf, &err_code);
2351
2352
  /* Not populated? */
2353
0
  if (!sub_git_dir) {
2354
0
    const struct submodule *sub;
2355
0
    struct strbuf sub_gitdir = STRBUF_INIT;
2356
2357
0
    if (err_code == READ_GITFILE_ERR_STAT_FAILED) {
2358
      /* unpopulated as expected */
2359
0
      strbuf_release(&gitdir);
2360
0
      return;
2361
0
    }
2362
2363
0
    if (err_code != READ_GITFILE_ERR_NOT_A_REPO)
2364
      /* We don't know what broke here. */
2365
0
      read_gitfile_error_die(err_code, path, NULL);
2366
2367
    /*
2368
    * Maybe populated, but no git directory was found?
2369
    * This can happen if the superproject is a submodule
2370
    * itself and was just absorbed. The absorption of the
2371
    * superproject did not rewrite the git file links yet,
2372
    * fix it now.
2373
    */
2374
0
    sub = submodule_from_path(the_repository, null_oid(), path);
2375
0
    if (!sub)
2376
0
      die(_("could not lookup name for submodule '%s'"), path);
2377
0
    submodule_name_to_gitdir(&sub_gitdir, the_repository, sub->name);
2378
0
    connect_work_tree_and_git_dir(path, sub_gitdir.buf, 0);
2379
0
    strbuf_release(&sub_gitdir);
2380
0
  } else {
2381
    /* Is it already absorbed into the superprojects git dir? */
2382
0
    char *real_sub_git_dir = real_pathdup(sub_git_dir, 1);
2383
0
    char *real_common_git_dir = real_pathdup(get_git_common_dir(), 1);
2384
2385
0
    if (!starts_with(real_sub_git_dir, real_common_git_dir))
2386
0
      relocate_single_git_dir_into_superproject(path, super_prefix);
2387
2388
0
    free(real_sub_git_dir);
2389
0
    free(real_common_git_dir);
2390
0
  }
2391
0
  strbuf_release(&gitdir);
2392
2393
0
  absorb_git_dir_into_superproject_recurse(path, super_prefix);
2394
0
}
2395
2396
int get_superproject_working_tree(struct strbuf *buf)
2397
0
{
2398
0
  struct child_process cp = CHILD_PROCESS_INIT;
2399
0
  struct strbuf sb = STRBUF_INIT;
2400
0
  struct strbuf one_up = STRBUF_INIT;
2401
0
  char *cwd = xgetcwd();
2402
0
  int ret = 0;
2403
0
  const char *subpath;
2404
0
  int code;
2405
0
  ssize_t len;
2406
2407
0
  if (!is_inside_work_tree())
2408
    /*
2409
     * FIXME:
2410
     * We might have a superproject, but it is harder
2411
     * to determine.
2412
     */
2413
0
    return 0;
2414
2415
0
  if (!strbuf_realpath(&one_up, "../", 0))
2416
0
    return 0;
2417
2418
0
  subpath = relative_path(cwd, one_up.buf, &sb);
2419
0
  strbuf_release(&one_up);
2420
2421
0
  prepare_submodule_repo_env(&cp.env);
2422
0
  strvec_pop(&cp.env);
2423
2424
0
  strvec_pushl(&cp.args, "--literal-pathspecs", "-C", "..",
2425
0
         "ls-files", "-z", "--stage", "--full-name", "--",
2426
0
         subpath, NULL);
2427
0
  strbuf_reset(&sb);
2428
2429
0
  cp.no_stdin = 1;
2430
0
  cp.no_stderr = 1;
2431
0
  cp.out = -1;
2432
0
  cp.git_cmd = 1;
2433
2434
0
  if (start_command(&cp))
2435
0
    die(_("could not start ls-files in .."));
2436
2437
0
  len = strbuf_read(&sb, cp.out, PATH_MAX);
2438
0
  close(cp.out);
2439
2440
0
  if (starts_with(sb.buf, "160000")) {
2441
0
    int super_sub_len;
2442
0
    int cwd_len = strlen(cwd);
2443
0
    char *super_sub, *super_wt;
2444
2445
    /*
2446
     * There is a superproject having this repo as a submodule.
2447
     * The format is <mode> SP <hash> SP <stage> TAB <full name> \0,
2448
     * We're only interested in the name after the tab.
2449
     */
2450
0
    super_sub = strchr(sb.buf, '\t') + 1;
2451
0
    super_sub_len = strlen(super_sub);
2452
2453
0
    if (super_sub_len > cwd_len ||
2454
0
        strcmp(&cwd[cwd_len - super_sub_len], super_sub))
2455
0
      BUG("returned path string doesn't match cwd?");
2456
2457
0
    super_wt = xstrdup(cwd);
2458
0
    super_wt[cwd_len - super_sub_len] = '\0';
2459
2460
0
    strbuf_realpath(buf, super_wt, 1);
2461
0
    ret = 1;
2462
0
    free(super_wt);
2463
0
  }
2464
0
  free(cwd);
2465
0
  strbuf_release(&sb);
2466
2467
0
  code = finish_command(&cp);
2468
2469
0
  if (code == 128)
2470
    /* '../' is not a git repository */
2471
0
    return 0;
2472
0
  if (code == 0 && len == 0)
2473
    /* There is an unrelated git repository at '../' */
2474
0
    return 0;
2475
0
  if (code)
2476
0
    die(_("ls-tree returned unexpected return code %d"), code);
2477
2478
0
  return ret;
2479
0
}
2480
2481
/*
2482
 * Put the gitdir for a submodule (given relative to the main
2483
 * repository worktree) into `buf`, or return -1 on error.
2484
 */
2485
int submodule_to_gitdir(struct strbuf *buf, const char *submodule)
2486
0
{
2487
0
  const struct submodule *sub;
2488
0
  const char *git_dir;
2489
0
  int ret = 0;
2490
2491
0
  strbuf_reset(buf);
2492
0
  strbuf_addstr(buf, submodule);
2493
0
  strbuf_complete(buf, '/');
2494
0
  strbuf_addstr(buf, ".git");
2495
2496
0
  git_dir = read_gitfile(buf->buf);
2497
0
  if (git_dir) {
2498
0
    strbuf_reset(buf);
2499
0
    strbuf_addstr(buf, git_dir);
2500
0
  }
2501
0
  if (!is_git_directory(buf->buf)) {
2502
0
    sub = submodule_from_path(the_repository, null_oid(),
2503
0
            submodule);
2504
0
    if (!sub) {
2505
0
      ret = -1;
2506
0
      goto cleanup;
2507
0
    }
2508
0
    strbuf_reset(buf);
2509
0
    submodule_name_to_gitdir(buf, the_repository, sub->name);
2510
0
  }
2511
2512
0
cleanup:
2513
0
  return ret;
2514
0
}
2515
2516
void submodule_name_to_gitdir(struct strbuf *buf, struct repository *r,
2517
            const char *submodule_name)
2518
0
{
2519
  /*
2520
   * NEEDSWORK: The current way of mapping a submodule's name to
2521
   * its location in .git/modules/ has problems with some naming
2522
   * schemes. For example, if a submodule is named "foo" and
2523
   * another is named "foo/bar" (whether present in the same
2524
   * superproject commit or not - the problem will arise if both
2525
   * superproject commits have been checked out at any point in
2526
   * time), or if two submodule names only have different cases in
2527
   * a case-insensitive filesystem.
2528
   *
2529
   * There are several solutions, including encoding the path in
2530
   * some way, introducing a submodule.<name>.gitdir config in
2531
   * .git/config (not .gitmodules) that allows overriding what the
2532
   * gitdir of a submodule would be (and teach Git, upon noticing
2533
   * a clash, to automatically determine a non-clashing name and
2534
   * to write such a config), or introducing a
2535
   * submodule.<name>.gitdir config in .gitmodules that repo
2536
   * administrators can explicitly set. Nothing has been decided,
2537
   * so for now, just append the name at the end of the path.
2538
   */
2539
0
  strbuf_repo_git_path(buf, r, "modules/");
2540
0
  strbuf_addstr(buf, submodule_name);
2541
0
}