Skip to content

Commit 194c3f1

Browse files
kbleesdscho
authored andcommitted
config.c: create missing parent directories when modifying config files
'git config' (--add / --unset etc.) automatically creates missing config files. However, it fails with a misleading error message "could not lock config file" if the parent directory doesn't exist. Also create missing parent directories. This is particularly important when calling git config -f /non/existing/directory/config ... Signed-off-by: Karsten Blees <[email protected]> Signed-off-by: Johannes Schindelin <[email protected]>
1 parent 0a666e0 commit 194c3f1

File tree

1 file changed

+21
-8
lines changed

1 file changed

+21
-8
lines changed

config.c

Lines changed: 21 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -1922,6 +1922,24 @@ int git_config_parse_key(const char *key, char **store_key, int *baselen_)
19221922
return -CONFIG_INVALID_KEY;
19231923
}
19241924

1925+
static int lock_config_file(const char *config_filename,
1926+
struct lock_file **result)
1927+
{
1928+
int fd;
1929+
1930+
/* make sure the parent directory exists */
1931+
if (safe_create_leading_directories_const(config_filename))
1932+
return error("could not create parent directory of %s",
1933+
config_filename);
1934+
*result = xcalloc(1, sizeof(struct lock_file));
1935+
fd = hold_lock_file_for_update(*result, config_filename, 0);
1936+
if (fd < 0)
1937+
error("could not lock config file %s: %s", config_filename,
1938+
strerror(errno));
1939+
1940+
return fd;
1941+
}
1942+
19251943
/*
19261944
* If value==NULL, unset in (remove from) config,
19271945
* if value_regex!=NULL, disregard key/value pairs where value does not match.
@@ -1970,10 +1988,8 @@ int git_config_set_multivar_in_file(const char *config_filename,
19701988
* The lock serves a purpose in addition to locking: the new
19711989
* contents of .git/config will be written into it.
19721990
*/
1973-
lock = xcalloc(1, sizeof(struct lock_file));
1974-
fd = hold_lock_file_for_update(lock, config_filename, 0);
1991+
fd = lock_config_file(config_filename, &lock);
19751992
if (fd < 0) {
1976-
error("could not lock config file %s: %s", config_filename, strerror(errno));
19771993
free(store.key);
19781994
ret = CONFIG_NO_LOCK;
19791995
goto out_free;
@@ -2241,12 +2257,9 @@ int git_config_rename_section_in_file(const char *config_filename,
22412257
if (!config_filename)
22422258
config_filename = filename_buf = git_pathdup("config");
22432259

2244-
lock = xcalloc(1, sizeof(struct lock_file));
2245-
out_fd = hold_lock_file_for_update(lock, config_filename, 0);
2246-
if (out_fd < 0) {
2247-
ret = error("could not lock config file %s", config_filename);
2260+
out_fd = lock_config_file(config_filename, &lock);
2261+
if (out_fd < 0)
22482262
goto out;
2249-
}
22502263

22512264
if (!(config_file = fopen(config_filename, "rb"))) {
22522265
/* no config file means nothing to rename, no error */

0 commit comments

Comments
 (0)