submodule: merge repo_read_gitmodules and gitmodules_config

Since 69aba5329 (submodule: add repo_read_gitmodules) there have been two ways to load a repository's .gitmodules file: 'repo_read_gitmodules()' is used if you have a repository object you are working with or 'gitmodules_config()' if you are implicitly working with 'the_repository'. Merge the logic of these two functions to remove duplicate code. In addition, 'repo_read_gitmodules()' can segfault by passing in a NULL pointer to 'git_config_from_file()' if a repository doesn't have a worktree. Instead check for the existence of a worktree before attempting to load the .gitmodules file. Signed-off-by: Brandon Williams <bmwill@google.com> Signed-off-by: Junio C Hamano <gitster@pobox.com>

Brandon Williams committed Aug 2, 2017 at 12:49 UTC 2184d4ba0cb86a7f40153cd46b03d3fa75b247d9
1 file changed +17 -20
submodule.c
+17 -20
@@ -230,23 +230,6 @@ void load_submodule_cache(void)
230 git_config(submodule_config, NULL);
231 }
232
233 -void gitmodules_config(void)
234 -{
235 - const char *work_tree = get_git_work_tree();
236 - if (work_tree) {
237 - struct strbuf gitmodules_path = STRBUF_INIT;
238 - strbuf_addstr(&gitmodules_path, work_tree);
239 - strbuf_addstr(&gitmodules_path, "/" GITMODULES_FILE);
240 - if (read_cache() < 0)
241 - die("index file corrupt");
242 -
243 - if (!is_gitmodules_unmerged(&the_index))
244 - git_config_from_file(git_modules_config,
245 - gitmodules_path.buf, NULL);
246 - strbuf_release(&gitmodules_path);
247 - }
248 -}
249 -
233 static int gitmodules_cb(const char *var, const char *value, void *data)
234 {
235 struct repository *repo = data;
@@ -255,10 +238,24 @@ static int gitmodules_cb(const char *var, const char *value, void *data)
238
239 void repo_read_gitmodules(struct repository *repo)
240 {
258 - char *gitmodules_path = repo_worktree_path(repo, GITMODULES_FILE);
241 + if (repo->worktree) {
242 + char *gitmodules;
243 +
244 + if (repo_read_index(repo) < 0)
245 + return;
246
260 - git_config_from_file(gitmodules_cb, gitmodules_path, repo);
261 - free(gitmodules_path);
247 + gitmodules = repo_worktree_path(repo, GITMODULES_FILE);
248 +
249 + if (!is_gitmodules_unmerged(repo->index))
250 + git_config_from_file(gitmodules_cb, gitmodules, repo);
251 +
252 + free(gitmodules);
253 + }
254 +}
255 +
256 +void gitmodules_config(void)
257 +{
258 + repo_read_gitmodules(the_repository);
259 }
260
261 void gitmodules_config_sha1(const unsigned char *commit_sha1)