submodule.c 50 KB
Newer Older
1
/*
Edward Thomson committed
2
 * Copyright (C) the libgit2 contributors. All rights reserved.
3 4 5 6 7 8 9
 *
 * This file is part of libgit2, distributed under the GNU GPL v2 with
 * a Linking Exception. For full terms see the included COPYING file.
 */

#include "common.h"
#include "git2/config.h"
10
#include "git2/sys/config.h"
11 12 13
#include "git2/types.h"
#include "git2/index.h"
#include "buffer.h"
14
#include "buf_text.h"
15 16 17 18 19
#include "vector.h"
#include "posix.h"
#include "config_file.h"
#include "config.h"
#include "repository.h"
Russell Belfer committed
20 21 22
#include "submodule.h"
#include "tree.h"
#include "iterator.h"
23 24
#include "path.h"
#include "index.h"
Russell Belfer committed
25 26

#define GIT_MODULES_FILE ".gitmodules"
27

28 29 30
static git_cvar_map _sm_update_map[] = {
	{GIT_CVAR_STRING, "checkout", GIT_SUBMODULE_UPDATE_CHECKOUT},
	{GIT_CVAR_STRING, "rebase", GIT_SUBMODULE_UPDATE_REBASE},
Russell Belfer committed
31 32
	{GIT_CVAR_STRING, "merge", GIT_SUBMODULE_UPDATE_MERGE},
	{GIT_CVAR_STRING, "none", GIT_SUBMODULE_UPDATE_NONE},
33 34
	{GIT_CVAR_FALSE, NULL, GIT_SUBMODULE_UPDATE_NONE},
	{GIT_CVAR_TRUE, NULL, GIT_SUBMODULE_UPDATE_CHECKOUT},
35 36
};

37
static git_cvar_map _sm_ignore_map[] = {
Russell Belfer committed
38
	{GIT_CVAR_STRING, "none", GIT_SUBMODULE_IGNORE_NONE},
39
	{GIT_CVAR_STRING, "untracked", GIT_SUBMODULE_IGNORE_UNTRACKED},
Russell Belfer committed
40 41
	{GIT_CVAR_STRING, "dirty", GIT_SUBMODULE_IGNORE_DIRTY},
	{GIT_CVAR_STRING, "all", GIT_SUBMODULE_IGNORE_ALL},
42 43
	{GIT_CVAR_FALSE, NULL, GIT_SUBMODULE_IGNORE_NONE},
	{GIT_CVAR_TRUE, NULL, GIT_SUBMODULE_IGNORE_ALL},
44 45
};

46 47 48 49 50 51
static git_cvar_map _sm_recurse_map[] = {
	{GIT_CVAR_STRING, "on-demand", GIT_SUBMODULE_RECURSE_ONDEMAND},
	{GIT_CVAR_FALSE, NULL, GIT_SUBMODULE_RECURSE_NO},
	{GIT_CVAR_TRUE, NULL, GIT_SUBMODULE_RECURSE_YES},
};

52 53 54 55 56 57 58 59 60 61
enum {
	CACHE_OK = 0,
	CACHE_REFRESH = 1,
	CACHE_FLUSH = 2
};
enum {
	GITMODULES_EXISTING = 0,
	GITMODULES_CREATE = 1,
};

62
static kh_inline khint_t str_hash_no_trailing_slash(const char *s)
63
{
64
	khint_t h;
65

66
	for (h = 0; *s; ++s)
67
		if (s[1] != '\0' || *s != '/')
68
			h = (h << 5) - h + *s;
69

70
	return h;
71 72
}

73
static kh_inline int str_equal_no_trailing_slash(const char *a, const char *b)
74
{
75 76
	size_t alen = a ? strlen(a) : 0;
	size_t blen = b ? strlen(b) : 0;
77

78
	if (alen > 0 && a[alen - 1] == '/')
79
		alen--;
80
	if (blen > 0 && b[blen - 1] == '/')
81 82
		blen--;

83
	return (alen == blen && strncmp(a, b, alen) == 0);
84 85
}

Russell Belfer committed
86 87
__KHASH_IMPL(
	str, static kh_inline, const char *, void *, 1,
88
	str_hash_no_trailing_slash, str_equal_no_trailing_slash)
Russell Belfer committed
89

90 91
static int submodule_alloc(git_submodule **out, git_repository *repo, const char *name);
static git_config_backend *open_gitmodules(git_repository *repo, int gitmod);
92 93
static int get_url_base(git_buf *url, git_repository *repo);
static int lookup_head_remote_key(git_buf *remote_key, git_repository *repo);
94
static int submodule_load_from_config(const git_config_entry *, void *);
95
static int submodule_load_from_wd_lite(git_submodule *);
96 97
static void submodule_get_index_status(unsigned int *, git_submodule *);
static void submodule_get_wd_status(unsigned int *, git_submodule *, git_repository *, git_submodule_ignore_t);
98 99
static void submodule_update_from_index_entry(git_submodule *sm, const git_index_entry *ie);
static void submodule_update_from_head_data(git_submodule *sm, mode_t mode, const git_oid *id);
Russell Belfer committed
100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116

static int submodule_cmp(const void *a, const void *b)
{
	return strcmp(((git_submodule *)a)->name, ((git_submodule *)b)->name);
}

static int submodule_config_key_trunc_puts(git_buf *key, const char *suffix)
{
	ssize_t idx = git_buf_rfind(key, '.');
	git_buf_truncate(key, (size_t)(idx + 1));
	return git_buf_puts(key, suffix);
}

/*
 * PUBLIC APIS
 */

117 118 119 120 121 122 123 124 125 126
static void submodule_set_lookup_error(int error, const char *name)
{
	if (!error)
		return;

	giterr_set(GITERR_SUBMODULE, (error == GIT_ENOTFOUND) ?
		"No submodule named '%s'" :
		"Submodule '%s' has not been added yet", name);
}

127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146
typedef struct {
	const char *path;
	char *name;
} fbp_data;

static int find_by_path(const git_config_entry *entry, void *payload)
{
	fbp_data *data = payload;

	if (!strcmp(entry->value, data->path)) {
		const char *fdot, *ldot;
		fdot = strchr(entry->name, '.');
		ldot = strrchr(entry->name, '.');
		data->name = git__strndup(fdot + 1, ldot - fdot - 1);
		GITERR_CHECK_ALLOC(data->name);
	}

	return 0;
}

147
int git_submodule_lookup(
148 149 150 151 152
	git_submodule **out, /* NULL if user only wants to test existence */
	git_repository *repo,
	const char *name)    /* trailing slash is allowed */
{
	int error;
153
	unsigned int location;
154
	git_submodule *sm;
155 156 157

	assert(repo && name);

158 159
	if ((error = submodule_alloc(&sm, repo, name)) < 0)
		return error;
Russell Belfer committed
160

161 162
	if ((error = git_submodule_reload(sm, false)) < 0) {
		git_submodule_free(sm);
Russell Belfer committed
163
		return error;
164
	}
Russell Belfer committed
165

166 167 168 169 170
	if ((error = git_submodule_location(&location, sm)) < 0) {
		git_submodule_free(sm);
		return error;
	}

171
	/* If it's not configured or we're looking by path  */
172 173
	if (location == 0 || location == GIT_SUBMODULE_STATUS_IN_WD) {
		git_config_backend *mods;
174
		const char *pattern = "submodule\\..*\\.path";
175 176 177 178 179 180 181 182
		git_buf path = GIT_BUF_INIT;
		fbp_data data = { NULL, NULL };

		git_buf_puts(&path, name);
		while (path.ptr[path.size-1] == '/') {
			path.ptr[--path.size] = '\0';
		}
		data.path = path.ptr;
183

184 185 186 187 188 189 190 191 192
		mods = open_gitmodules(repo, GITMODULES_EXISTING);

		if (mods)
			error = git_config_file_foreach_match(mods, pattern, find_by_path, &data);

		git_config_file_free(mods);

		if (error < 0) {
			git_submodule_free(sm);
193
			return error;
194
		}
195 196 197 198

		if (data.name) {
			git__free(sm->name);
			sm->name = data.name;
199
			sm->path = git_buf_detach(&path);
200 201 202 203 204 205 206

			/* Try to load again with the right name */
			if ((error = git_submodule_reload(sm, false)) < 0) {
				git_submodule_free(sm);
				return error;
			}
		}
207 208

		git_buf_free(&path);
209 210
	}

211 212 213 214 215 216 217
	if ((error = git_submodule_location(&location, sm)) < 0) {
		git_submodule_free(sm);
		return error;
	}

	/* If we still haven't found it, do the WD check */
	if (location == 0 || location == GIT_SUBMODULE_STATUS_IN_WD) {
218 219
		git_submodule_free(sm);
		error = GIT_ENOTFOUND;
Russell Belfer committed
220

221
		/* If it's not configured, we still check if there's a repo at the path */
Russell Belfer committed
222 223
		if (git_repository_workdir(repo)) {
			git_buf path = GIT_BUF_INIT;
224
			if (git_buf_join3(&path,
225
					  '/', git_repository_workdir(repo), name, DOT_GIT) < 0)
Russell Belfer committed
226 227
				return -1;

228
			if (git_path_exists(path.ptr))
Russell Belfer committed
229 230 231 232 233
				error = GIT_EEXISTS;

			git_buf_free(&path);
		}

234
		submodule_set_lookup_error(error, name);
235
		return error;
Russell Belfer committed
236 237
	}

238 239 240 241 242 243
	if (out)
		*out = sm;
	else
		git_submodule_free(sm);

	return 0;
Russell Belfer committed
244
}
245

246 247 248 249 250
static void submodule_free_dup(void *sm)
{
	git_submodule_free(sm);
}

251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438
static int submodule_get_or_create(git_submodule **out, git_repository *repo, git_strmap *map, const char *name)
{
	int error = 0;
	khiter_t pos;
	git_submodule *sm = NULL;

	pos = git_strmap_lookup_index(map, name);
	if (git_strmap_valid_index(map, pos)) {
		sm = git_strmap_value_at(map, pos);
		goto done;
	}

	/* if the submodule doesn't exist yet in the map, create it */
	if ((error = submodule_alloc(&sm, repo, name)) < 0)
		return error;

	pos = kh_put(str, map, sm->name, &error);
	/* nobody can beat us to adding it */
	assert(error != 0);
	if (error < 0) {
		git_submodule_free(sm);
		return error;
	}

	git_strmap_set_value_at(map, pos, sm);

done:
	GIT_REFCOUNT_INC(sm);
	*out = sm;
	return 0;
}

static int submodules_from_index(git_strmap *map, git_index *idx)
{
       int error;
       git_iterator *i;
       const git_index_entry *entry;

       if ((error = git_iterator_for_index(&i, idx, 0, NULL, NULL)) < 0)
               return error;

       while (!(error = git_iterator_advance(&entry, i))) {
               khiter_t pos = git_strmap_lookup_index(map, entry->path);
               git_submodule *sm;

               if (git_strmap_valid_index(map, pos)) {
                       sm = git_strmap_value_at(map, pos);

                       if (S_ISGITLINK(entry->mode))
                               submodule_update_from_index_entry(sm, entry);
                       else
                               sm->flags |= GIT_SUBMODULE_STATUS__INDEX_NOT_SUBMODULE;
               } else if (S_ISGITLINK(entry->mode)) {
                       if (!submodule_get_or_create(&sm, git_index_owner(idx), map, entry->path)) {
                               submodule_update_from_index_entry(sm, entry);
                               git_submodule_free(sm);
                       }
               }
       }

       if (error == GIT_ITEROVER)
               error = 0;

       git_iterator_free(i);

       return error;
}

static int submodules_from_head(git_strmap *map, git_tree *head)
{
       int error;
       git_iterator *i;
       const git_index_entry *entry;

       if ((error = git_iterator_for_tree(&i, head, 0, NULL, NULL)) < 0)
               return error;

       while (!(error = git_iterator_advance(&entry, i))) {
               khiter_t pos = git_strmap_lookup_index(map, entry->path);
               git_submodule *sm;

               if (git_strmap_valid_index(map, pos)) {
                       sm = git_strmap_value_at(map, pos);

                       if (S_ISGITLINK(entry->mode))
                               submodule_update_from_head_data(sm, entry->mode, &entry->id);
                       else
                               sm->flags |= GIT_SUBMODULE_STATUS__HEAD_NOT_SUBMODULE;
               } else if (S_ISGITLINK(entry->mode)) {
                       if (!submodule_get_or_create(&sm, git_tree_owner(head), map, entry->path)) {
                               submodule_update_from_head_data(
                                       sm, entry->mode, &entry->id);
                               git_submodule_free(sm);
                       }
               }
       }

       if (error == GIT_ITEROVER)
               error = 0;

       git_iterator_free(i);

       return error;
}

/* If have_sm is true, sm is populated, otherwise map an repo are. */
typedef struct {
	int have_sm;
	git_submodule *sm;
	git_strmap *map;
	git_repository *repo;
} lfc_data;

static int all_submodules(git_repository *repo, git_strmap *map)
{
	int error = 0;
	git_index *idx = NULL;
	git_tree *head = NULL;
	const char *wd = NULL;
	git_buf path = GIT_BUF_INIT;
	git_submodule *sm;
	git_config_backend *mods = NULL;
	uint32_t mask;

	assert(repo && map);

	/* get sources that we will need to check */
	if (git_repository_index(&idx, repo) < 0)
		giterr_clear();
	if (git_repository_head_tree(&head, repo) < 0)
		giterr_clear();

	wd = git_repository_workdir(repo);
	if (wd && (error = git_buf_joinpath(&path, wd, GIT_MODULES_FILE)) < 0)
		goto cleanup;

	/* clear submodule flags that are to be refreshed */
	mask = 0;
	mask |= GIT_SUBMODULE_STATUS_IN_INDEX |
		GIT_SUBMODULE_STATUS__INDEX_FLAGS |
		GIT_SUBMODULE_STATUS__INDEX_OID_VALID |
		GIT_SUBMODULE_STATUS__INDEX_MULTIPLE_ENTRIES;

	mask |= GIT_SUBMODULE_STATUS_IN_HEAD |
		GIT_SUBMODULE_STATUS__HEAD_OID_VALID;
	mask |= GIT_SUBMODULE_STATUS_IN_CONFIG;
	if (mask != 0)
		mask |= GIT_SUBMODULE_STATUS_IN_WD |
			GIT_SUBMODULE_STATUS__WD_SCANNED |
			GIT_SUBMODULE_STATUS__WD_FLAGS |
			GIT_SUBMODULE_STATUS__WD_OID_VALID;

	/* add back submodule information from index */
	if (idx) {
		if ((error = submodules_from_index(map, idx)) < 0)
			goto cleanup;
	}
	/* add submodule information from HEAD */
	if (head) {
		if ((error = submodules_from_head(map, head)) < 0)
			goto cleanup;
	}
	/* add submodule information from .gitmodules */
	if (wd) {
		lfc_data data = { 0 };
		data.map = map;
		data.repo = repo;
		if ((mods = open_gitmodules(repo, false)) != NULL &&
		    (error = git_config_file_foreach(
			    mods, submodule_load_from_config, &data)) < 0)
			goto cleanup;
	}
	/* shallow scan submodules in work tree as needed */
	if (wd && mask != 0) {
		git_strmap_foreach_value(map, sm, {
				submodule_load_from_wd_lite(sm);
			});
	}

cleanup:
	git_config_file_free(mods);
	/* TODO: if we got an error, mark submodule config as invalid? */
	git_index_free(idx);
	git_tree_free(head);
	git_buf_free(&path);
	return error;
}

Russell Belfer committed
439 440 441 442 443
int git_submodule_foreach(
	git_repository *repo,
	int (*callback)(git_submodule *sm, const char *name, void *payload),
	void *payload)
{
444 445 446
	git_vector snapshot = GIT_VECTOR_INIT;
	git_strmap *submodules;
	git_submodule *sm;
Russell Belfer committed
447
	int error;
448
	size_t i;
Russell Belfer committed
449

450
	if ((error = git_strmap_alloc(&submodules)) < 0)
Russell Belfer committed
451 452
		return error;

453 454
	if ((error = all_submodules(repo, submodules)) < 0)
		goto done;
455 456

	if (!(error = git_vector_init(
457
			&snapshot, kh_size(submodules), submodule_cmp))) {
458

459
		git_strmap_foreach_value(submodules, sm, {
460
			if ((error = git_vector_insert(&snapshot, sm)) < 0)
Russell Belfer committed
461
				break;
462 463 464 465 466 467 468 469 470 471
			GIT_REFCOUNT_INC(sm);
		});
	}

	if (error < 0)
		goto done;

	git_vector_uniq(&snapshot, submodule_free_dup);

	git_vector_foreach(&snapshot, i, sm) {
472
		if ((error = callback(sm, sm->name, payload)) != 0) {
473
			giterr_set_after_callback(error);
Russell Belfer committed
474
			break;
475
		}
476
	}
Russell Belfer committed
477

478 479 480 481
done:
	git_vector_foreach(&snapshot, i, sm)
		git_submodule_free(sm);
	git_vector_free(&snapshot);
Russell Belfer committed
482

483 484 485 486
	git_strmap_foreach_value(submodules, sm, {
		git_submodule_free(sm);
	});
	git_strmap_free(submodules);
Russell Belfer committed
487

488
	return error;
Russell Belfer committed
489 490
}

491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540
static int submodule_repo_init(
	git_repository **out,
	git_repository *parent_repo,
	const char *path,
	const char *url,
	bool use_gitlink)
{
	int error = 0;
	git_buf workdir = GIT_BUF_INIT, repodir = GIT_BUF_INIT;
	git_repository_init_options initopt = GIT_REPOSITORY_INIT_OPTIONS_INIT;
	git_repository *subrepo = NULL;

	error = git_buf_joinpath(&workdir, git_repository_workdir(parent_repo), path);
	if (error < 0)
		goto cleanup;

	initopt.flags = GIT_REPOSITORY_INIT_MKPATH | GIT_REPOSITORY_INIT_NO_REINIT;
	initopt.origin_url = url;

	/* init submodule repository and add origin remote as needed */

	/* New style: sub-repo goes in <repo-dir>/modules/<name>/ with a
	 * gitlink in the sub-repo workdir directory to that repository
	 *
	 * Old style: sub-repo goes directly into repo/<name>/.git/
	 */
	 if (use_gitlink) {
		error = git_buf_join3(
			&repodir, '/', git_repository_path(parent_repo), "modules", path);
		if (error < 0)
			goto cleanup;

		initopt.workdir_path = workdir.ptr;
		initopt.flags |=
			GIT_REPOSITORY_INIT_NO_DOTGIT_DIR |
			GIT_REPOSITORY_INIT_RELATIVE_GITLINK;

		error = git_repository_init_ext(&subrepo, repodir.ptr, &initopt);
	} else
		error = git_repository_init_ext(&subrepo, workdir.ptr, &initopt);

cleanup:
	git_buf_free(&workdir);
	git_buf_free(&repodir);

	*out = subrepo;

	return error;
}

Russell Belfer committed
541
int git_submodule_add_setup(
542
	git_submodule **out,
Russell Belfer committed
543 544 545 546 547 548
	git_repository *repo,
	const char *url,
	const char *path,
	int use_gitlink)
{
	int error = 0;
Ben Straub committed
549
	git_config_backend *mods = NULL;
550
	git_submodule *sm = NULL;
Russell Belfer committed
551 552 553 554 555 556 557
	git_buf name = GIT_BUF_INIT, real_url = GIT_BUF_INIT;
	git_repository *subrepo = NULL;

	assert(repo && url && path);

	/* see if there is already an entry for this submodule */

558
	if (git_submodule_lookup(NULL, repo, path) < 0)
Russell Belfer committed
559 560 561
		giterr_clear();
	else {
		giterr_set(GITERR_SUBMODULE,
562
			"Attempt to add submodule '%s' that already exists", path);
Russell Belfer committed
563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578
		return GIT_EEXISTS;
	}

	/* validate and normalize path */

	if (git__prefixcmp(path, git_repository_workdir(repo)) == 0)
		path += strlen(git_repository_workdir(repo));

	if (git_path_root(path) >= 0) {
		giterr_set(GITERR_SUBMODULE, "Submodule path must be a relative path");
		error = -1;
		goto cleanup;
	}

	/* update .gitmodules */

579
	if (!(mods = open_gitmodules(repo, GITMODULES_CREATE))) {
Russell Belfer committed
580
		giterr_set(GITERR_SUBMODULE,
581
			"Adding submodules to a bare repository is not supported");
Russell Belfer committed
582 583 584 585 586 587 588 589
		return -1;
	}

	if ((error = git_buf_printf(&name, "submodule.%s.path", path)) < 0 ||
		(error = git_config_file_set_string(mods, name.ptr, path)) < 0)
		goto cleanup;

	if ((error = submodule_config_key_trunc_puts(&name, "url")) < 0 ||
590
		(error = git_config_file_set_string(mods, name.ptr, url)) < 0)
Russell Belfer committed
591 592 593 594 595 596 597 598 599 600
		goto cleanup;

	git_buf_clear(&name);

	/* init submodule repository and add origin remote as needed */

	error = git_buf_joinpath(&name, git_repository_workdir(repo), path);
	if (error < 0)
		goto cleanup;

601 602
	/* if the repo does not already exist, then init a new repo and add it.
	 * Otherwise, just add the existing repo.
Russell Belfer committed
603
	 */
604 605
	if (!(git_path_exists(name.ptr) &&
		git_path_contains(&name, DOT_GIT))) {
606 607 608 609 610 611

		/* resolve the actual URL to use */
		if ((error = git_submodule_resolve_url(&real_url, repo, url)) < 0)
			goto cleanup;

		 if ((error = submodule_repo_init(&subrepo, repo, path, real_url.ptr, use_gitlink)) < 0)
Russell Belfer committed
612 613 614
			goto cleanup;
	}

615
	if ((error = git_submodule_lookup(&sm, repo, path)) < 0)
616
		goto cleanup;
Russell Belfer committed
617

618
	error = git_submodule_init(sm, false);
619

Russell Belfer committed
620
cleanup:
621 622 623 624 625 626
	if (error && sm) {
		git_submodule_free(sm);
		sm = NULL;
	}
	if (out != NULL)
		*out = sm;
Russell Belfer committed
627

628
	git_config_file_free(mods);
Russell Belfer committed
629 630 631 632 633 634 635
	git_repository_free(subrepo);
	git_buf_free(&real_url);
	git_buf_free(&name);

	return error;
}

636 637 638 639 640 641 642
int git_submodule_repo_init(
	git_repository **out,
	const git_submodule *sm,
	int use_gitlink)
{
	int error;
	git_repository *sub_repo = NULL;
643 644 645
	const char *configured_url;
	git_config *cfg = NULL;
	git_buf buf = GIT_BUF_INIT;
646 647 648

	assert(out && sm);

649 650
	/* get the configured remote url of the submodule */
	if ((error = git_buf_printf(&buf, "submodule.%s.url", sm->name)) < 0 ||
651
		(error = git_repository_config_snapshot(&cfg, sm->repo)) < 0 ||
652 653 654
		(error = git_config_get_string(&configured_url, cfg, buf.ptr)) < 0 ||
		(error = submodule_repo_init(&sub_repo, sm->repo, sm->path, configured_url, use_gitlink)) < 0)
		goto done;
655 656 657

	*out = sub_repo;

658 659 660
done:
	git_config_free(cfg);
	git_buf_free(&buf);
661 662 663
	return error;
}

Russell Belfer committed
664 665 666 667 668 669 670
int git_submodule_add_finalize(git_submodule *sm)
{
	int error;
	git_index *index;

	assert(sm);

671
	if ((error = git_repository_index__weakptr(&index, sm->repo)) < 0 ||
672
		(error = git_index_add_bypath(index, GIT_MODULES_FILE)) < 0)
Russell Belfer committed
673 674
		return error;

675
	return git_submodule_add_to_index(sm, true);
Russell Belfer committed
676 677
}

678
int git_submodule_add_to_index(git_submodule *sm, int write_index)
Russell Belfer committed
679 680
{
	int error;
681
	git_repository *sm_repo = NULL;
Russell Belfer committed
682 683 684 685 686 687 688 689
	git_index *index;
	git_buf path = GIT_BUF_INIT;
	git_commit *head;
	git_index_entry entry;
	struct stat st;

	assert(sm);

690 691 692
	/* force reload of wd OID by git_submodule_open */
	sm->flags = sm->flags & ~GIT_SUBMODULE_STATUS__WD_OID_VALID;

693
	if ((error = git_repository_index__weakptr(&index, sm->repo)) < 0 ||
Russell Belfer committed
694
		(error = git_buf_joinpath(
695
			&path, git_repository_workdir(sm->repo), sm->path)) < 0 ||
Russell Belfer committed
696 697 698 699 700 701 702 703 704 705
		(error = git_submodule_open(&sm_repo, sm)) < 0)
		goto cleanup;

	/* read stat information for submodule working directory */
	if (p_stat(path.ptr, &st) < 0) {
		giterr_set(GITERR_SUBMODULE,
			"Cannot add submodule without working directory");
		error = -1;
		goto cleanup;
	}
706 707

	memset(&entry, 0, sizeof(entry));
708
	entry.path = sm->path;
709 710
	git_index_entry__init_from_stat(
		&entry, &st, !(git_index_caps(index) & GIT_INDEXCAP_NO_FILEMODE));
Russell Belfer committed
711 712 713 714 715 716 717 718

	/* calling git_submodule_open will have set sm->wd_oid if possible */
	if ((sm->flags & GIT_SUBMODULE_STATUS__WD_OID_VALID) == 0) {
		giterr_set(GITERR_SUBMODULE,
			"Cannot add submodule without HEAD to index");
		error = -1;
		goto cleanup;
	}
719
	git_oid_cpy(&entry.id, &sm->wd_oid);
Russell Belfer committed
720 721 722 723 724 725 726 727 728 729 730

	if ((error = git_commit_lookup(&head, sm_repo, &sm->wd_oid)) < 0)
		goto cleanup;

	entry.ctime.seconds = git_commit_time(head);
	entry.ctime.nanoseconds = 0;
	entry.mtime.seconds = git_commit_time(head);
	entry.mtime.nanoseconds = 0;

	git_commit_free(head);

731
	/* add it */
Edward Thomson committed
732
	error = git_index_add(index, &entry);
Russell Belfer committed
733

734 735 736 737 738 739 740 741
	/* write it, if requested */
	if (!error && write_index) {
		error = git_index_write(index);

		if (!error)
			git_oid_cpy(&sm->index_oid, &sm->wd_oid);
	}

Russell Belfer committed
742 743 744 745 746 747
cleanup:
	git_repository_free(sm_repo);
	git_buf_free(&path);
	return error;
}

748 749 750 751
const char *git_submodule_update_to_str(git_submodule_update_t update)
{
	int i;
	for (i = 0; i < (int)ARRAY_SIZE(_sm_update_map); ++i)
752
		if (_sm_update_map[i].map_value == (int)update)
753 754 755 756
			return _sm_update_map[i].str_match;
	return NULL;
}

Russell Belfer committed
757 758 759
git_repository *git_submodule_owner(git_submodule *submodule)
{
	assert(submodule);
760
	return submodule->repo;
Russell Belfer committed
761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780
}

const char *git_submodule_name(git_submodule *submodule)
{
	assert(submodule);
	return submodule->name;
}

const char *git_submodule_path(git_submodule *submodule)
{
	assert(submodule);
	return submodule->path;
}

const char *git_submodule_url(git_submodule *submodule)
{
	assert(submodule);
	return submodule->url;
}

781 782 783 784
int git_submodule_resolve_url(git_buf *out, git_repository *repo, const char *url)
{
	int error = 0;

785 786 787
	assert(out && repo && url);

	git_buf_sanitize(out);
Carlos Martín Nieto committed
788

789
	if (git_path_is_relative(url)) {
790
		if (!(error = get_url_base(out, repo)))
791 792 793 794 795 796 797 798 799 800 801
			error = git_path_apply_relative(out, url);
	} else if (strchr(url, ':') != NULL || url[0] == '/') {
		error = git_buf_sets(out, url);
	} else {
		giterr_set(GITERR_SUBMODULE, "Invalid format for submodule URL");
		error = -1;
	}

	return error;
}

802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826
static int write_var(git_repository *repo, const char *name, const char *var, const char *val)
{
	git_buf key = GIT_BUF_INIT;
	git_config_backend *mods;
	int error;

	mods = open_gitmodules(repo, GITMODULES_CREATE);
	if (!mods)
		return -1;

	if ((error = git_buf_printf(&key, "submodule.%s.%s", name, var)) < 0)
		goto cleanup;

	if (val)
		error = git_config_file_set_string(mods, key.ptr, val);
	else
		error = git_config_file_delete(mods, key.ptr);

	git_buf_free(&key);

cleanup:
	git_config_file_free(mods);
	return error;
}

827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842
static int write_mapped_var(git_repository *repo, const char *name, git_cvar_map *maps, size_t nmaps, const char *var, int ival)
{
	git_cvar_t type;
	const char *val;

	if (git_config_lookup_map_enum(&type, &val, maps, nmaps, ival) < 0) {
		giterr_set(GITERR_SUBMODULE, "invalid value for %s", var);
		return -1;
	}

	if (type == GIT_CVAR_TRUE)
		val = "true";

	return write_var(repo, name, var, val);
}

843 844 845 846 847 848
const char *git_submodule_branch(git_submodule *submodule)
{
	assert(submodule);
	return submodule->branch;
}

849
int git_submodule_set_branch(git_repository *repo, const char *name, const char *branch)
850 851
{

852
	assert(repo && name);
853

854
	return write_var(repo, name, "branch", branch);
855 856
}

857
int git_submodule_set_url(git_repository *repo, const char *name, const char *url)
Russell Belfer committed
858
{
859
	assert(repo && name && url);
Russell Belfer committed
860

861
	return write_var(repo, name, "url", url);
Russell Belfer committed
862 863
}

864
const git_oid *git_submodule_index_id(git_submodule *submodule)
Russell Belfer committed
865 866 867 868 869 870 871 872 873
{
	assert(submodule);

	if (submodule->flags & GIT_SUBMODULE_STATUS__INDEX_OID_VALID)
		return &submodule->index_oid;
	else
		return NULL;
}

874
const git_oid *git_submodule_head_id(git_submodule *submodule)
Russell Belfer committed
875 876 877 878 879 880 881 882 883
{
	assert(submodule);

	if (submodule->flags & GIT_SUBMODULE_STATUS__HEAD_OID_VALID)
		return &submodule->head_oid;
	else
		return NULL;
}

884
const git_oid *git_submodule_wd_id(git_submodule *submodule)
Russell Belfer committed
885 886 887
{
	assert(submodule);

888
	/* load unless we think we have a valid oid */
Russell Belfer committed
889 890 891 892
	if (!(submodule->flags & GIT_SUBMODULE_STATUS__WD_OID_VALID)) {
		git_repository *subrepo;

		/* calling submodule open grabs the HEAD OID if possible */
893
		if (!git_submodule_open_bare(&subrepo, submodule))
Russell Belfer committed
894
			git_repository_free(subrepo);
895 896
		else
			giterr_clear();
Russell Belfer committed
897 898 899 900 901 902 903 904 905 906 907
	}

	if (submodule->flags & GIT_SUBMODULE_STATUS__WD_OID_VALID)
		return &submodule->wd_oid;
	else
		return NULL;
}

git_submodule_ignore_t git_submodule_ignore(git_submodule *submodule)
{
	assert(submodule);
908 909
	return (submodule->ignore < GIT_SUBMODULE_IGNORE_NONE) ?
		GIT_SUBMODULE_IGNORE_NONE : submodule->ignore;
Russell Belfer committed
910 911
}

912 913
int git_submodule_set_ignore(git_repository *repo, const char *name, git_submodule_ignore_t ignore)
{
914
	assert(repo && name);
915

916
	return write_mapped_var(repo, name, _sm_ignore_map, ARRAY_SIZE(_sm_ignore_map), "ignore", ignore);
917 918
}

919
git_submodule_update_t git_submodule_update_strategy(git_submodule *submodule)
Russell Belfer committed
920 921
{
	assert(submodule);
922 923
	return (submodule->update < GIT_SUBMODULE_UPDATE_CHECKOUT) ?
		GIT_SUBMODULE_UPDATE_CHECKOUT : submodule->update;
Russell Belfer committed
924 925
}

926
int git_submodule_set_update(git_repository *repo, const char *name, git_submodule_update_t update)
Russell Belfer committed
927
{
928
	assert(repo && name);
Russell Belfer committed
929

930
	return write_mapped_var(repo, name, _sm_update_map, ARRAY_SIZE(_sm_update_map), "update", update);
Russell Belfer committed
931 932
}

933
git_submodule_recurse_t git_submodule_fetch_recurse_submodules(
934 935 936 937 938 939
	git_submodule *submodule)
{
	assert(submodule);
	return submodule->fetch_recurse;
}

940
int git_submodule_set_fetch_recurse_submodules(git_repository *repo, const char *name, git_submodule_recurse_t recurse)
941
{
942 943
	assert(repo && name);

944
	return write_mapped_var(repo, name, _sm_recurse_map, ARRAY_SIZE(_sm_recurse_map), "fetchRecurseSubmodules", recurse);
945 946
}

947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000
static int submodule_repo_create(
	git_repository **out,
	git_repository *parent_repo,
	const char *path)
{
	int error = 0;
	git_buf workdir = GIT_BUF_INIT, repodir = GIT_BUF_INIT;
	git_repository_init_options initopt = GIT_REPOSITORY_INIT_OPTIONS_INIT;
	git_repository *subrepo = NULL;

	initopt.flags =
		GIT_REPOSITORY_INIT_MKPATH |
		GIT_REPOSITORY_INIT_NO_REINIT |
		GIT_REPOSITORY_INIT_NO_DOTGIT_DIR |
		GIT_REPOSITORY_INIT_RELATIVE_GITLINK;

	/* Workdir: path to sub-repo working directory */
	error = git_buf_joinpath(&workdir, git_repository_workdir(parent_repo), path);
	if (error < 0)
		goto cleanup;

	initopt.workdir_path = workdir.ptr;

	/**
	 * Repodir: path to the sub-repo. sub-repo goes in:
	 * <repo-dir>/modules/<name>/ with a gitlink in the 
	 * sub-repo workdir directory to that repository.
	 */
	error = git_buf_join3(
		&repodir, '/', git_repository_path(parent_repo), "modules", path);
	if (error < 0)
		goto cleanup;

	error = git_repository_init_ext(&subrepo, repodir.ptr, &initopt);

cleanup:
	git_buf_free(&workdir);
	git_buf_free(&repodir);

	*out = subrepo;

	return error;
}

/**
 * Callback to override sub-repository creation when
 * cloning a sub-repository.
 */
static int git_submodule_update_repo_init_cb(
	git_repository **out,
	const char *path,
	int bare,
	void *payload)
{
1001 1002
	git_submodule *sm;

1003
	GIT_UNUSED(bare);
1004 1005

	sm = payload;
1006 1007 1008 1009

	return submodule_repo_create(out, sm->repo, path);
}

1010 1011 1012 1013 1014 1015 1016
int git_submodule_update_init_options(git_submodule_update_options *opts, unsigned int version)
{
	GIT_INIT_STRUCTURE_FROM_TEMPLATE(
		opts, version, git_submodule_update_options, GIT_SUBMODULE_UPDATE_OPTIONS_INIT);
	return 0;
}

1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037
int git_submodule_update(git_submodule *sm, int init, git_submodule_update_options *_update_options)
{
	int error;
	unsigned int submodule_status;
	git_config *config = NULL;
	const char *submodule_url;
	git_repository *sub_repo = NULL;
	git_remote *remote = NULL;
	git_object *target_commit = NULL;
	git_buf buf = GIT_BUF_INIT;
	git_submodule_update_options update_options = GIT_SUBMODULE_UPDATE_OPTIONS_INIT;
	git_clone_options clone_options = GIT_CLONE_OPTIONS_INIT;

	assert(sm);

	if (_update_options)
		memcpy(&update_options, _update_options, sizeof(git_submodule_update_options));

	GITERR_CHECK_VERSION(&update_options, GIT_SUBMODULE_UPDATE_OPTIONS_VERSION, "git_submodule_update_options");

	/* Copy over the remote callbacks */
1038
	memcpy(&clone_options.fetch_opts, &update_options.fetch_opts, sizeof(git_fetch_options));
1039 1040

	/* Get the status of the submodule to determine if it is already initialized  */
1041
	if ((error = git_submodule_status(&submodule_status, sm->repo, sm->name, GIT_SUBMODULE_IGNORE_UNSPECIFIED)) < 0)
1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095
		goto done;

	/*
	 * If submodule work dir is not already initialized, check to see
	 * what we need to do (initialize, clone, return error...)
	 */
	if (submodule_status & GIT_SUBMODULE_STATUS_WD_UNINITIALIZED) {
		/*
		 * Work dir is not initialized, check to see if the submodule
		 * info has been copied into .git/config
		 */
		if ((error = git_repository_config_snapshot(&config, sm->repo)) < 0 ||
			(error = git_buf_printf(&buf, "submodule.%s.url", git_submodule_name(sm))) < 0)
			goto done;

		if ((error = git_config_get_string(&submodule_url, config, git_buf_cstr(&buf))) < 0) {
			/*
			 * If the error is not "not found" or if it is "not found" and we are not
			 * initializing the submodule, then return error.
			 */
			if (error != GIT_ENOTFOUND)
				goto done;

			if (error == GIT_ENOTFOUND && !init) {
				giterr_set(GITERR_SUBMODULE, "Submodule is not initialized.");
				error = GIT_ERROR;
				goto done;
			}

			/* The submodule has not been initialized yet - initialize it now.*/
			if ((error = git_submodule_init(sm, 0)) < 0)
				goto done;

			git_config_free(config);
			config = NULL;

			if ((error = git_repository_config_snapshot(&config, sm->repo)) < 0 ||
				(error = git_config_get_string(&submodule_url, config, git_buf_cstr(&buf))) < 0)
				goto done;
		}

		/** submodule is initialized - now clone it **/
		/* override repo creation */
		clone_options.repository_cb = git_submodule_update_repo_init_cb;
		clone_options.repository_cb_payload = sm;

		/*
		 * Do not perform checkout as part of clone, instead we 
		 * will checkout the specific commit manually.
		 */
		clone_options.checkout_opts.checkout_strategy = GIT_CHECKOUT_NONE;
		update_options.checkout_opts.checkout_strategy = update_options.clone_checkout_strategy;

		if ((error = git_clone(&sub_repo, submodule_url, sm->path, &clone_options)) < 0 ||
1096
			(error = git_repository_set_head_detached(sub_repo, git_submodule_index_id(sm))) < 0 ||
1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107
			(error = git_checkout_head(sub_repo, &update_options.checkout_opts)) != 0)
			goto done;
	} else {
		/**
		 * Work dir is initialized - look up the commit in the parent repository's index,
		 * update the workdir contents of the subrepository, and set the subrepository's
		 * head to the new commit.
		 */
		if ((error = git_submodule_open(&sub_repo, sm)) < 0 ||
			(error = git_object_lookup(&target_commit, sub_repo, git_submodule_index_id(sm), GIT_OBJ_COMMIT)) < 0 ||
			(error = git_checkout_tree(sub_repo, target_commit, &update_options.checkout_opts)) != 0 ||
1108
			(error = git_repository_set_head_detached(sub_repo, git_submodule_index_id(sm))) < 0)
1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127
			goto done;

		/* Invalidate the wd flags as the workdir has been updated. */
		sm->flags = sm->flags &
			~(GIT_SUBMODULE_STATUS_IN_WD |
		  	GIT_SUBMODULE_STATUS__WD_OID_VALID |
		  	GIT_SUBMODULE_STATUS__WD_SCANNED);
	}

done:
	git_buf_free(&buf);
	git_config_free(config);
	git_object_free(target_commit);
	git_remote_free(remote);
	git_repository_free(sub_repo);

	return error;
}

1128
int git_submodule_init(git_submodule *sm, int overwrite)
Russell Belfer committed
1129 1130
{
	int error;
1131
	const char *val;
1132
	git_buf key = GIT_BUF_INIT, effective_submodule_url = GIT_BUF_INIT;
1133
	git_config *cfg = NULL;
Russell Belfer committed
1134

1135
	if (!sm->url) {
Russell Belfer committed
1136
		giterr_set(GITERR_SUBMODULE,
1137
			"No URL configured for submodule '%s'", sm->name);
Russell Belfer committed
1138 1139 1140
		return -1;
	}

1141
	if ((error = git_repository_config(&cfg, sm->repo)) < 0)
Russell Belfer committed
1142 1143
		return error;

1144 1145
	/* write "submodule.NAME.url" */

1146
	if ((error = git_submodule_resolve_url(&effective_submodule_url, sm->repo, sm->url)) < 0 ||
1147
		(error = git_buf_printf(&key, "submodule.%s.url", sm->name)) < 0 ||
1148
		(error = git_config__update_entry(
1149
			cfg, key.ptr, effective_submodule_url.ptr, overwrite != 0, false)) < 0)
1150 1151
		goto cleanup;

Russell Belfer committed
1152 1153
	/* write "submodule.NAME.update" if not default */

1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166
	val = (sm->update == GIT_SUBMODULE_UPDATE_CHECKOUT) ?
		NULL : git_submodule_update_to_str(sm->update);

	if ((error = git_buf_printf(&key, "submodule.%s.update", sm->name)) < 0 ||
		(error = git_config__update_entry(
			cfg, key.ptr, val, overwrite != 0, false)) < 0)
		goto cleanup;

	/* success */

cleanup:
	git_config_free(cfg);
	git_buf_free(&key);
1167
	git_buf_free(&effective_submodule_url);
Russell Belfer committed
1168 1169 1170 1171

	return error;
}

1172
int git_submodule_sync(git_submodule *sm)
Russell Belfer committed
1173
{
1174 1175 1176
	int error = 0;
	git_config *cfg = NULL;
	git_buf key = GIT_BUF_INIT;
1177
	git_repository *smrepo = NULL;
1178 1179

	if (!sm->url) {
Russell Belfer committed
1180
		giterr_set(GITERR_SUBMODULE,
1181
			"No URL configured for submodule '%s'", sm->name);
Russell Belfer committed
1182 1183 1184 1185 1186
		return -1;
	}

	/* copy URL over to config only if it already exists */

1187 1188 1189 1190 1191 1192
	if (!(error = git_repository_config__weakptr(&cfg, sm->repo)) &&
		!(error = git_buf_printf(&key, "submodule.%s.url", sm->name)))
		error = git_config__update_entry(cfg, key.ptr, sm->url, true, true);

	/* if submodule exists in the working directory, update remote url */

1193 1194 1195 1196
	if (!error &&
		(sm->flags & GIT_SUBMODULE_STATUS_IN_WD) != 0 &&
		!(error = git_submodule_open(&smrepo, sm)))
	{
1197 1198 1199 1200 1201
		git_buf remote_name = GIT_BUF_INIT;

		if ((error = git_repository_config__weakptr(&cfg, smrepo)) < 0)
			/* return error from reading submodule config */;
		else if ((error = lookup_head_remote_key(&remote_name, smrepo)) < 0) {
1202
			giterr_clear();
1203
			error = git_buf_sets(&key, "remote.origin.url");
1204 1205
		} else {
			error = git_buf_join3(
1206
				&key, '.', "remote", remote_name.ptr, "url");
1207
			git_buf_free(&remote_name);
1208 1209
		}

1210 1211
		if (!error)
			error = git_config__update_entry(cfg, key.ptr, sm->url, true, false);
1212 1213 1214 1215 1216 1217 1218

		git_repository_free(smrepo);
	}

	git_buf_free(&key);

	return error;
Russell Belfer committed
1219 1220
}

1221 1222
static int git_submodule__open(
	git_repository **subrepo, git_submodule *sm, bool bare)
Russell Belfer committed
1223 1224 1225
{
	int error;
	git_buf path = GIT_BUF_INIT;
1226 1227
	unsigned int flags = GIT_REPOSITORY_OPEN_NO_SEARCH;
	const char *wd;
Russell Belfer committed
1228

1229
	assert(sm && subrepo);
Russell Belfer committed
1230

1231 1232 1233
	if (git_repository__ensure_not_bare(
			sm->repo, "open submodule repository") < 0)
		return GIT_EBAREREPO;
Russell Belfer committed
1234

1235
	wd = git_repository_workdir(sm->repo);
Russell Belfer committed
1236

1237 1238
	if (git_buf_joinpath(&path, wd, sm->path) < 0 ||
		git_buf_joinpath(&path, path.ptr, DOT_GIT) < 0)
Russell Belfer committed
1239 1240
		return -1;

1241 1242 1243 1244
	sm->flags = sm->flags &
		~(GIT_SUBMODULE_STATUS_IN_WD |
		  GIT_SUBMODULE_STATUS__WD_OID_VALID |
		  GIT_SUBMODULE_STATUS__WD_SCANNED);
Russell Belfer committed
1245

1246 1247
	if (bare)
		flags |= GIT_REPOSITORY_OPEN_BARE;
Russell Belfer committed
1248

1249
	error = git_repository_open_ext(subrepo, path.ptr, flags, wd);
1250

1251 1252 1253 1254
	/* if we opened the submodule successfully, grab HEAD OID, etc. */
	if (!error) {
		sm->flags |= GIT_SUBMODULE_STATUS_IN_WD |
			GIT_SUBMODULE_STATUS__WD_SCANNED;
1255

1256 1257 1258 1259 1260 1261 1262 1263 1264
		if (!git_reference_name_to_id(&sm->wd_oid, *subrepo, GIT_HEAD_FILE))
			sm->flags |= GIT_SUBMODULE_STATUS__WD_OID_VALID;
		else
			giterr_clear();
	} else if (git_path_exists(path.ptr)) {
		sm->flags |= GIT_SUBMODULE_STATUS__WD_SCANNED |
			GIT_SUBMODULE_STATUS_IN_WD;
	} else {
		git_buf_rtruncate_at_char(&path, '/'); /* remove "/.git" */
1265

1266 1267 1268
		if (git_path_isdir(path.ptr))
			sm->flags |= GIT_SUBMODULE_STATUS__WD_SCANNED;
	}
1269

1270
	git_buf_free(&path);
1271

1272 1273
	return error;
}
1274

1275 1276 1277 1278
int git_submodule_open_bare(git_repository **subrepo, git_submodule *sm)
{
	return git_submodule__open(subrepo, sm, true);
}
Russell Belfer committed
1279

1280 1281 1282
int git_submodule_open(git_repository **subrepo, git_submodule *sm)
{
	return git_submodule__open(subrepo, sm, false);
Russell Belfer committed
1283 1284
}

1285 1286
static void submodule_update_from_index_entry(
	git_submodule *sm, const git_index_entry *ie)
Russell Belfer committed
1287
{
1288
	bool already_found = (sm->flags & GIT_SUBMODULE_STATUS_IN_INDEX) != 0;
Russell Belfer committed
1289

1290 1291 1292 1293 1294 1295 1296
	if (!S_ISGITLINK(ie->mode)) {
		if (!already_found)
			sm->flags |= GIT_SUBMODULE_STATUS__INDEX_NOT_SUBMODULE;
	} else {
		if (already_found)
			sm->flags |= GIT_SUBMODULE_STATUS__INDEX_MULTIPLE_ENTRIES;
		else
1297
			git_oid_cpy(&sm->index_oid, &ie->id);
Russell Belfer committed
1298

1299 1300 1301 1302 1303 1304 1305 1306 1307
		sm->flags |= GIT_SUBMODULE_STATUS_IN_INDEX |
			GIT_SUBMODULE_STATUS__INDEX_OID_VALID;
	}
}

static int submodule_update_index(git_submodule *sm)
{
	git_index *index;
	const git_index_entry *ie;
Russell Belfer committed
1308

1309
	if (git_repository_index__weakptr(&index, sm->repo) < 0)
Russell Belfer committed
1310 1311
		return -1;

1312
	sm->flags = sm->flags &
1313 1314 1315
		~(GIT_SUBMODULE_STATUS_IN_INDEX |
		  GIT_SUBMODULE_STATUS__INDEX_OID_VALID);

1316 1317
	if (!(ie = git_index_get_bypath(index, sm->path, 0)))
		return 0;
Russell Belfer committed
1318

1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333
	submodule_update_from_index_entry(sm, ie);

	return 0;
}

static void submodule_update_from_head_data(
	git_submodule *sm, mode_t mode, const git_oid *id)
{
	if (!S_ISGITLINK(mode))
		sm->flags |= GIT_SUBMODULE_STATUS__HEAD_NOT_SUBMODULE;
	else {
		git_oid_cpy(&sm->head_oid, id);

		sm->flags |= GIT_SUBMODULE_STATUS_IN_HEAD |
			GIT_SUBMODULE_STATUS__HEAD_OID_VALID;
Russell Belfer committed
1334
	}
1335
}
Russell Belfer committed
1336

1337 1338 1339
static int submodule_update_head(git_submodule *submodule)
{
	git_tree *head = NULL;
nulltoken committed
1340
	git_tree_entry *te = NULL;
Russell Belfer committed
1341

1342 1343 1344
	submodule->flags = submodule->flags &
		~(GIT_SUBMODULE_STATUS_IN_HEAD |
		  GIT_SUBMODULE_STATUS__HEAD_OID_VALID);
Russell Belfer committed
1345

1346 1347 1348 1349 1350 1351
	/* if we can't look up file in current head, then done */
	if (git_repository_head_tree(&head, submodule->repo) < 0 ||
		git_tree_entry_bypath(&te, head, submodule->path) < 0)
		giterr_clear();
	else
		submodule_update_from_head_data(submodule, te->attr, &te->oid);
Russell Belfer committed
1352

nulltoken committed
1353
	git_tree_entry_free(te);
1354 1355 1356
	git_tree_free(head);
	return 0;
}
1357

1358

1359
int git_submodule_reload(git_submodule *sm, int force)
1360 1361 1362
{
	int error = 0;
	git_config_backend *mods;
1363
	lfc_data data = { 0 };
Russell Belfer committed
1364

1365 1366
	GIT_UNUSED(force);

1367 1368
	assert(sm);

1369
	/* refresh index data */
1370
	if ((error = submodule_update_index(sm)) < 0)
1371
		return error;
1372 1373

	/* refresh HEAD tree data */
1374
	if ((error = submodule_update_head(sm)) < 0)
1375
		return error;
Russell Belfer committed
1376

1377
	/* done if bare */
1378
	if (git_repository_is_bare(sm->repo))
1379 1380
		return error;

Russell Belfer committed
1381
	/* refresh config data */
1382
	mods = open_gitmodules(sm->repo, GITMODULES_EXISTING);
1383
	if (mods != NULL) {
Russell Belfer committed
1384 1385 1386
		git_buf path = GIT_BUF_INIT;

		git_buf_sets(&path, "submodule\\.");
1387
		git_buf_text_puts_escape_regex(&path, sm->name);
1388
		git_buf_puts(&path, "\\..*");
Russell Belfer committed
1389

1390
		if (git_buf_oom(&path)) {
Russell Belfer committed
1391
			error = -1;
1392 1393 1394
		} else {
			data.have_sm = 1;
			data.sm = sm;
Russell Belfer committed
1395
			error = git_config_file_foreach_match(
1396 1397
				mods, path.ptr, submodule_load_from_config, &data);
		}
Russell Belfer committed
1398 1399

		git_buf_free(&path);
1400
		git_config_file_free(mods);
Russell Belfer committed
1401

1402 1403 1404
		if (error < 0)
			return error;
	}
1405 1406

	/* refresh wd data */
1407 1408 1409
	sm->flags &=
		~(GIT_SUBMODULE_STATUS_IN_WD | GIT_SUBMODULE_STATUS__WD_OID_VALID |
		  GIT_SUBMODULE_STATUS__WD_FLAGS);
1410

1411
	return submodule_load_from_wd_lite(sm);
Russell Belfer committed
1412 1413
}

1414 1415
static void submodule_copy_oid_maybe(
	git_oid *tgt, const git_oid *src, bool valid)
Russell Belfer committed
1416
{
1417 1418 1419 1420 1421 1422 1423
	if (tgt) {
		if (valid)
			memcpy(tgt, src, sizeof(*tgt));
		else
			memset(tgt, 0, sizeof(*tgt));
	}
}
1424

1425 1426 1427 1428 1429 1430 1431 1432 1433 1434
int git_submodule__status(
	unsigned int *out_status,
	git_oid *out_head_id,
	git_oid *out_index_id,
	git_oid *out_wd_id,
	git_submodule *sm,
	git_submodule_ignore_t ign)
{
	unsigned int status;
	git_repository *smrepo = NULL;
Russell Belfer committed
1435

1436
	if (ign == GIT_SUBMODULE_IGNORE_UNSPECIFIED)
1437
		ign = sm->ignore;
1438

1439 1440 1441 1442
	/* only return location info if ignore == all */
	if (ign == GIT_SUBMODULE_IGNORE_ALL) {
		*out_status = (sm->flags & GIT_SUBMODULE_STATUS__IN_FLAGS);
		return 0;
1443
	}
Russell Belfer committed
1444

1445 1446 1447 1448 1449 1450 1451
	/* refresh the index OID */
	if (submodule_update_index(sm) < 0)
		return -1;

	/* refresh the HEAD OID */
	if (submodule_update_head(sm) < 0)
		return -1;
Russell Belfer committed
1452

1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482
	/* for ignore == dirty, don't scan the working directory */
	if (ign == GIT_SUBMODULE_IGNORE_DIRTY) {
		/* git_submodule_open_bare will load WD OID data */
		if (git_submodule_open_bare(&smrepo, sm) < 0)
			giterr_clear();
		else
			git_repository_free(smrepo);
		smrepo = NULL;
	} else if (git_submodule_open(&smrepo, sm) < 0) {
		giterr_clear();
		smrepo = NULL;
	}

	status = GIT_SUBMODULE_STATUS__CLEAR_INTERNAL(sm->flags);

	submodule_get_index_status(&status, sm);
	submodule_get_wd_status(&status, sm, smrepo, ign);

	git_repository_free(smrepo);

	*out_status = status;

	submodule_copy_oid_maybe(out_head_id, &sm->head_oid,
		(sm->flags & GIT_SUBMODULE_STATUS__HEAD_OID_VALID) != 0);
	submodule_copy_oid_maybe(out_index_id, &sm->index_oid,
		(sm->flags & GIT_SUBMODULE_STATUS__INDEX_OID_VALID) != 0);
	submodule_copy_oid_maybe(out_wd_id, &sm->wd_oid,
		(sm->flags & GIT_SUBMODULE_STATUS__WD_OID_VALID) != 0);

	return 0;
Russell Belfer committed
1483 1484
}

1485
int git_submodule_status(unsigned int *status, git_repository *repo, const char *name, git_submodule_ignore_t ignore)
1486
{
1487 1488 1489 1490 1491 1492 1493 1494
	git_submodule *sm;
	int error;

	assert(status && repo && name);

	if ((error = git_submodule_lookup(&sm, repo, name)) < 0)
		return error;

1495
	error = git_submodule__status(status, NULL, NULL, NULL, sm, ignore);
1496
	git_submodule_free(sm);
1497

1498
	return error;
1499
}
1500

1501 1502 1503 1504 1505 1506
int git_submodule_location(unsigned int *location, git_submodule *sm)
{
	assert(location && sm);

	return git_submodule__status(
		location, NULL, NULL, NULL, sm, GIT_SUBMODULE_IGNORE_ALL);
1507 1508 1509
}


Russell Belfer committed
1510 1511 1512 1513
/*
 * INTERNAL FUNCTIONS
 */

1514
static int submodule_alloc(
1515
	git_submodule **out, git_repository *repo, const char *name)
1516
{
1517
	size_t namelen;
1518
	git_submodule *sm;
1519

1520
	if (!name || !(namelen = strlen(name))) {
1521
		giterr_set(GITERR_SUBMODULE, "Invalid submodule name");
1522
		return -1;
1523 1524
	}

1525
	sm = git__calloc(1, sizeof(git_submodule));
1526
	GITERR_CHECK_ALLOC(sm);
1527

1528 1529 1530
	sm->name = sm->path = git__strdup(name);
	if (!sm->name) {
		git__free(sm);
1531
		return -1;
1532
	}
Russell Belfer committed
1533

1534
	GIT_REFCOUNT_INC(sm);
1535 1536
	sm->ignore = sm->ignore_default = GIT_SUBMODULE_IGNORE_NONE;
	sm->update = sm->update_default = GIT_SUBMODULE_UPDATE_CHECKOUT;
1537
	sm->fetch_recurse = sm->fetch_recurse_default = GIT_SUBMODULE_RECURSE_NO;
1538
	sm->repo   = repo;
1539
	sm->branch = NULL;
1540

1541 1542
	*out = sm;
	return 0;
Russell Belfer committed
1543 1544
}

1545
static void submodule_release(git_submodule *sm)
Russell Belfer committed
1546 1547 1548 1549
{
	if (!sm)
		return;

1550
	if (sm->repo) {
1551
		sm->repo = NULL;
1552 1553
	}

1554 1555 1556 1557
	if (sm->path != sm->name)
		git__free(sm->path);
	git__free(sm->name);
	git__free(sm->url);
1558
	git__free(sm->branch);
1559 1560 1561
	git__memzero(sm, sizeof(*sm));
	git__free(sm);
}
Russell Belfer committed
1562

1563 1564 1565 1566 1567
void git_submodule_free(git_submodule *sm)
{
	if (!sm)
		return;
	GIT_REFCOUNT_DEC(sm, submodule_release);
Russell Belfer committed
1568 1569
}

1570 1571 1572 1573 1574
static int submodule_config_error(const char *property, const char *value)
{
	giterr_set(GITERR_INVALID,
		"Invalid value for submodule '%s' property: '%s'", property, value);
	return -1;
1575 1576
}

1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604
int git_submodule_parse_ignore(git_submodule_ignore_t *out, const char *value)
{
	int val;

	if (git_config_lookup_map_value(
			&val, _sm_ignore_map, ARRAY_SIZE(_sm_ignore_map), value) < 0) {
		*out = GIT_SUBMODULE_IGNORE_NONE;
		return submodule_config_error("ignore", value);
	}

	*out = (git_submodule_ignore_t)val;
	return 0;
}

int git_submodule_parse_update(git_submodule_update_t *out, const char *value)
{
	int val;

	if (git_config_lookup_map_value(
			&val, _sm_update_map, ARRAY_SIZE(_sm_update_map), value) < 0) {
		*out = GIT_SUBMODULE_UPDATE_CHECKOUT;
		return submodule_config_error("update", value);
	}

	*out = (git_submodule_update_t)val;
	return 0;
}

1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618
int git_submodule_parse_recurse(git_submodule_recurse_t *out, const char *value)
{
	int val;

	if (git_config_lookup_map_value(
			&val, _sm_recurse_map, ARRAY_SIZE(_sm_recurse_map), value) < 0) {
		*out = GIT_SUBMODULE_RECURSE_YES;
		return submodule_config_error("recurse", value);
	}

	*out = (git_submodule_recurse_t)val;
	return 0;
}

Russell Belfer committed
1619
static int submodule_load_from_config(
1620
	const git_config_entry *entry, void *payload)
1621
{
1622
	const char *namestart, *property;
1623
	const char *key = entry->name, *value = entry->value, *path;
1624
	char *alternate = NULL, *replaced = NULL;
1625
	git_buf name = GIT_BUF_INIT;
1626 1627
	lfc_data *data = payload;
	git_submodule *sm;
1628
	int error = 0;
1629 1630 1631 1632 1633 1634

	if (git__prefixcmp(key, "submodule.") != 0)
		return 0;

	namestart = key + strlen("submodule.");
	property  = strrchr(namestart, '.');
1635 1636

	if (!property || (property == namestart))
1637
		return 0;
1638

1639
	property++;
1640
	path = !strcasecmp(property, "path") ? value : NULL;
1641

1642
	if ((error = git_buf_set(&name, namestart, property - namestart -1)) < 0)
1643
		goto done;
1644

1645 1646 1647 1648 1649
	if (data->have_sm) {
		sm = data->sm;
	} else {
		khiter_t pos;
		git_strmap *map = data->map;
1650
		pos = git_strmap_lookup_index(map, path ? path : name.ptr);
1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664
		if (git_strmap_valid_index(map, pos)) {
			sm = git_strmap_value_at(map, pos);
		} else {
			if ((error = submodule_alloc(&sm, data->repo, name.ptr)) < 0)
				goto done;

			git_strmap_insert(map, sm->name, sm, error);
			assert(error != 0);
			if (error < 0)
				goto done;
			error = 0;
		}
	}

Russell Belfer committed
1665 1666
	sm->flags |= GIT_SUBMODULE_STATUS_IN_CONFIG;

1667 1668 1669
	/* Only from config might we get differing names & paths.  If so, then
	 * update the submodule and insert under the alternative key.
	 */
1670

1671 1672 1673
	/* TODO: if case insensitive filesystem, then the following strcmps
	 * should be strcasecmp
	 */
1674

1675
	if (strcmp(sm->name, name.ptr) != 0) { /* name changed */
1676
		if (sm->path && !strcmp(sm->path, name.ptr)) { /* already set as path */
1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696
			replaced = sm->name;
			sm->name = sm->path;
		} else {
			if (sm->name != sm->path)
				replaced = sm->name;
			alternate = sm->name = git_buf_detach(&name);
		}
	}
	else if (path && strcmp(path, sm->path) != 0) { /* path changed */
		if (!strcmp(sm->name, value)) { /* already set as name */
			replaced = sm->path;
			sm->path = sm->name;
		} else {
			if (sm->path != sm->name)
				replaced = sm->path;
			if ((alternate = git__strdup(value)) == NULL) {
				error = -1;
				goto done;
			}
			sm->path = alternate;
1697
		}
1698
	}
1699

1700 1701 1702 1703 1704
	/* Deregister under name being replaced */
	if (replaced) {
		git__free(replaced);
	}

Russell Belfer committed
1705 1706 1707 1708
	/* TODO: Look up path in index and if it is present but not a GITLINK
	 * then this should be deleted (at least to match git's behavior)
	 */

1709
	if (path)
1710
		goto done;
1711 1712

	/* copy other properties into submodule entry */
Russell Belfer committed
1713
	if (strcasecmp(property, "url") == 0) {
1714 1715 1716
		git__free(sm->url);
		sm->url = NULL;

1717 1718 1719 1720
		if (value != NULL && (sm->url = git__strdup(value)) == NULL) {
			error = -1;
			goto done;
		}
1721
	}
1722 1723 1724 1725 1726 1727 1728 1729 1730
	else if (strcasecmp(property, "branch") == 0) {
		git__free(sm->branch);
		sm->branch = NULL;

		if (value != NULL && (sm->branch = git__strdup(value)) == NULL) {
			error = -1;
			goto done;
		}
	}
Russell Belfer committed
1731
	else if (strcasecmp(property, "update") == 0) {
1732 1733
		if ((error = git_submodule_parse_update(&sm->update, value)) < 0)
			goto done;
1734
		sm->update_default = sm->update;
1735
	}
Russell Belfer committed
1736
	else if (strcasecmp(property, "fetchRecurseSubmodules") == 0) {
1737 1738
		if ((error = git_submodule_parse_recurse(&sm->fetch_recurse, value)) < 0)
			goto done;
1739
		sm->fetch_recurse_default = sm->fetch_recurse;
1740
	}
Russell Belfer committed
1741
	else if (strcasecmp(property, "ignore") == 0) {
1742 1743
		if ((error = git_submodule_parse_ignore(&sm->ignore, value)) < 0)
			goto done;
1744
		sm->ignore_default = sm->ignore;
1745 1746 1747
	}
	/* ignore other unknown submodule properties */

1748 1749
done:
	git_buf_free(&name);
1750
	return error;
1751 1752
}

1753
static int submodule_load_from_wd_lite(git_submodule *sm)
Russell Belfer committed
1754 1755 1756
{
	git_buf path = GIT_BUF_INIT;

1757
	if (git_buf_joinpath(&path, git_repository_workdir(sm->repo), sm->path) < 0)
1758
		return -1;
Russell Belfer committed
1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769

	if (git_path_isdir(path.ptr))
		sm->flags |= GIT_SUBMODULE_STATUS__WD_SCANNED;

	if (git_path_contains(&path, DOT_GIT))
		sm->flags |= GIT_SUBMODULE_STATUS_IN_WD;

	git_buf_free(&path);
	return 0;
}

Ben Straub committed
1770
static git_config_backend *open_gitmodules(
1771
	git_repository *repo,
1772
	int okay_to_create)
Russell Belfer committed
1773
{
1774
	const char *workdir = git_repository_workdir(repo);
Russell Belfer committed
1775
	git_buf path = GIT_BUF_INIT;
Ben Straub committed
1776
	git_config_backend *mods = NULL;
Russell Belfer committed
1777 1778 1779 1780 1781 1782 1783 1784

	if (workdir != NULL) {
		if (git_buf_joinpath(&path, workdir, GIT_MODULES_FILE) != 0)
			return NULL;

		if (okay_to_create || git_path_isfile(path.ptr)) {
			/* git_config_file__ondisk should only fail if OOM */
			if (git_config_file__ondisk(&mods, path.ptr) < 0)
1785
				mods = NULL;
Russell Belfer committed
1786
			/* open should only fail here if the file is malformed */
1787
			else if (git_config_file_open(mods, GIT_CONFIG_LEVEL_LOCAL) < 0) {
Russell Belfer committed
1788 1789 1790
				git_config_file_free(mods);
				mods = NULL;
			}
1791 1792 1793
		}
	}

1794 1795
	git_buf_free(&path);

Russell Belfer committed
1796 1797 1798
	return mods;
}

Russell Belfer committed
1799 1800
/* Lookup name of remote of the local tracking branch HEAD points to */
static int lookup_head_remote_key(git_buf *remote_name, git_repository *repo)
1801
{
Russell Belfer committed
1802
	int error;
Russell Belfer committed
1803 1804 1805 1806 1807 1808 1809
	git_reference *head = NULL;
	git_buf upstream_name = GIT_BUF_INIT;

	/* lookup and dereference HEAD */
	if ((error = git_repository_head(&head, repo)) < 0)
		return error;

1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821
	/**
	 * If head does not refer to a branch, then return
	 * GIT_ENOTFOUND to indicate that we could not find
	 * a remote key for the local tracking branch HEAD points to.
	 **/
	if (!git_reference_is_branch(head)) {
		giterr_set(GITERR_INVALID,
			"HEAD does not refer to a branch.");
		error = GIT_ENOTFOUND;
		goto done;
	}

Russell Belfer committed
1822
	/* lookup remote tracking branch of HEAD */
1823 1824 1825 1826 1827
	if ((error = git_branch_upstream_name(
		&upstream_name,
		repo,
		git_reference_name(head))) < 0)
		goto done;
Russell Belfer committed
1828

1829 1830 1831
	/* lookup remote of remote tracking branch */
	if ((error = git_branch_remote_name(remote_name, repo, upstream_name.ptr)) < 0)
		goto done;
Russell Belfer committed
1832

1833 1834
done:
	git_buf_free(&upstream_name);
Russell Belfer committed
1835
	git_reference_free(head);
1836

1837 1838
	return error;
}
1839

Russell Belfer committed
1840 1841
/* Lookup the remote of the local tracking branch HEAD points to */
static int lookup_head_remote(git_remote **remote, git_repository *repo)
1842 1843
{
	int error;
Russell Belfer committed
1844
	git_buf remote_name = GIT_BUF_INIT;
1845

Russell Belfer committed
1846 1847
	/* lookup remote of remote tracking branch name */
	if (!(error = lookup_head_remote_key(&remote_name, repo)))
1848
		error = git_remote_lookup(remote, repo, remote_name.ptr);
1849

Russell Belfer committed
1850
	git_buf_free(&remote_name);
Russell Belfer committed
1851

1852 1853
	return error;
}
Russell Belfer committed
1854

Russell Belfer committed
1855 1856
/* Lookup remote, either from HEAD or fall back on origin */
static int lookup_default_remote(git_remote **remote, git_repository *repo)
1857
{
Russell Belfer committed
1858
	int error = lookup_head_remote(remote, repo);
Russell Belfer committed
1859

Russell Belfer committed
1860 1861
	/* if that failed, use 'origin' instead */
	if (error == GIT_ENOTFOUND)
1862
		error = git_remote_lookup(remote, repo, "origin");
Russell Belfer committed
1863

Russell Belfer committed
1864 1865 1866 1867 1868
	if (error == GIT_ENOTFOUND)
		giterr_set(
			GITERR_SUBMODULE,
			"Cannot get default remote for submodule - no local tracking "
			"branch for HEAD and origin does not exist");
Russell Belfer committed
1869 1870

	return error;
1871 1872
}

Russell Belfer committed
1873
static int get_url_base(git_buf *url, git_repository *repo)
1874 1875
{
	int error;
Russell Belfer committed
1876
	git_remote *remote = NULL;
1877

Russell Belfer committed
1878 1879 1880 1881 1882 1883 1884 1885 1886
	if (!(error = lookup_default_remote(&remote, repo))) {
		error = git_buf_sets(url, git_remote_url(remote));
		git_remote_free(remote);
	}
	else if (error == GIT_ENOTFOUND) {
		/* if repository does not have a default remote, use workdir instead */
		giterr_clear();
		error = git_buf_sets(url, git_repository_workdir(repo));
	}
1887 1888 1889 1890

	return error;
}

1891
static void submodule_get_index_status(unsigned int *status, git_submodule *sm)
Russell Belfer committed
1892
{
1893 1894
	const git_oid *head_oid  = git_submodule_head_id(sm);
	const git_oid *index_oid = git_submodule_index_id(sm);
Russell Belfer committed
1895

1896 1897
	*status = *status & ~GIT_SUBMODULE_STATUS__INDEX_FLAGS;

1898 1899 1900 1901 1902 1903 1904 1905
	if (!head_oid) {
		if (index_oid)
			*status |= GIT_SUBMODULE_STATUS_INDEX_ADDED;
	}
	else if (!index_oid)
		*status |= GIT_SUBMODULE_STATUS_INDEX_DELETED;
	else if (!git_oid_equal(head_oid, index_oid))
		*status |= GIT_SUBMODULE_STATUS_INDEX_MODIFIED;
Russell Belfer committed
1906 1907
}

1908

1909 1910 1911 1912 1913
static void submodule_get_wd_status(
	unsigned int *status,
	git_submodule *sm,
	git_repository *sm_repo,
	git_submodule_ignore_t ign)
1914
{
1915 1916 1917 1918
	const git_oid *index_oid = git_submodule_index_id(sm);
	const git_oid *wd_oid =
		(sm->flags & GIT_SUBMODULE_STATUS__WD_OID_VALID) ? &sm->wd_oid : NULL;
	git_tree *sm_head = NULL;
1919
	git_index *index = NULL;
1920
	git_diff_options opt = GIT_DIFF_OPTIONS_INIT;
1921
	git_diff *diff;
1922

1923
	*status = *status & ~GIT_SUBMODULE_STATUS__WD_FLAGS;
Russell Belfer committed
1924

1925 1926 1927
	if (!index_oid) {
		if (wd_oid)
			*status |= GIT_SUBMODULE_STATUS_WD_ADDED;
Russell Belfer committed
1928
	}
1929 1930 1931 1932 1933 1934
	else if (!wd_oid) {
		if ((sm->flags & GIT_SUBMODULE_STATUS__WD_SCANNED) != 0 &&
			(sm->flags & GIT_SUBMODULE_STATUS_IN_WD) == 0)
			*status |= GIT_SUBMODULE_STATUS_WD_UNINITIALIZED;
		else
			*status |= GIT_SUBMODULE_STATUS_WD_DELETED;
Russell Belfer committed
1935
	}
1936 1937
	else if (!git_oid_equal(index_oid, wd_oid))
		*status |= GIT_SUBMODULE_STATUS_WD_MODIFIED;
Russell Belfer committed
1938

1939 1940 1941
	/* if we have no repo, then we're done */
	if (!sm_repo)
		return;
1942

1943 1944 1945 1946
	/* the diffs below could be optimized with an early termination
	 * option to the git_diff functions, but for now this is sufficient
	 * (and certainly no worse that what core git does).
	 */
1947

1948 1949
	if (ign == GIT_SUBMODULE_IGNORE_NONE)
		opt.flags |= GIT_DIFF_INCLUDE_UNTRACKED;
Russell Belfer committed
1950

1951 1952
	(void)git_repository_index__weakptr(&index, sm_repo);

1953
	/* if we don't have an unborn head, check diff with index */
1954 1955 1956 1957
	if (git_repository_head_tree(&sm_head, sm_repo) < 0)
		giterr_clear();
	else {
		/* perform head to index diff on submodule */
1958
		if (git_diff_tree_to_index(&diff, sm_repo, sm_head, index, &opt) < 0)
1959 1960
			giterr_clear();
		else {
1961
			if (git_diff_num_deltas(diff) > 0)
1962
				*status |= GIT_SUBMODULE_STATUS_WD_INDEX_MODIFIED;
1963
			git_diff_free(diff);
1964 1965
			diff = NULL;
		}
Russell Belfer committed
1966

1967
		git_tree_free(sm_head);
1968
	}
1969

1970
	/* perform index-to-workdir diff on submodule */
1971
	if (git_diff_index_to_workdir(&diff, sm_repo, index, &opt) < 0)
1972 1973 1974 1975
		giterr_clear();
	else {
		size_t untracked =
			git_diff_num_deltas_of_type(diff, GIT_DELTA_UNTRACKED);
1976

1977 1978
		if (untracked > 0)
			*status |= GIT_SUBMODULE_STATUS_WD_UNTRACKED;
1979

1980 1981
		if (git_diff_num_deltas(diff) != untracked)
			*status |= GIT_SUBMODULE_STATUS_WD_WD_MODIFIED;
Russell Belfer committed
1982

1983
		git_diff_free(diff);
1984
		diff = NULL;
1985
	}
1986
}