Coverage Report

Created: 2026-01-09 07:10

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