Skip to content

Commit 406614a

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 8cdfe60 commit 406614a

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.
@@ -1972,10 +1990,8 @@ int git_config_set_multivar_in_file(const char *config_filename,
19721990
* The lock serves a purpose in addition to locking: the new
19731991
* contents of .git/config will be written into it.
19741992
*/
1975-
lock = xcalloc(1, sizeof(struct lock_file));
1976-
fd = hold_lock_file_for_update(lock, config_filename, 0);
1993+
fd = lock_config_file(config_filename, &lock);
19771994
if (fd < 0) {
1978-
error("could not lock config file %s: %s", config_filename, strerror(errno));
19791995
free(store.key);
19801996
ret = CONFIG_NO_LOCK;
19811997
goto out_free;
@@ -2251,12 +2267,9 @@ int git_config_rename_section_in_file(const char *config_filename,
22512267
if (!config_filename)
22522268
config_filename = filename_buf = git_pathdup("config");
22532269

2254-
lock = xcalloc(1, sizeof(struct lock_file));
2255-
out_fd = hold_lock_file_for_update(lock, config_filename, 0);
2256-
if (out_fd < 0) {
2257-
ret = error("could not lock config file %s", config_filename);
2270+
out_fd = lock_config_file(config_filename, &lock);
2271+
if (out_fd < 0)
22582272
goto out;
2259-
}
22602273

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

0 commit comments

Comments
 (0)