# HG changeset patch # User Rob Landley # Date 1331172336 21600 # Node ID a864aa8c6331b16cd7f211b7a2c01a0cb691416f # Parent 31215cc6c9f22c9781f50618d0e7a0373ec26083 Fix mkdir -p to accept paths that already exist, and detect path ending in a file. diff -r 31215cc6c9f2 -r a864aa8c6331 toys/mkdir.c --- a/toys/mkdir.c Wed Mar 07 19:04:50 2012 -0600 +++ b/toys/mkdir.c Wed Mar 07 20:05:36 2012 -0600 @@ -30,21 +30,35 @@ static int do_mkdir(char *dir) { - unsigned int i; + struct stat buf; + char *s; - if (toys.optflags && *dir) { - // Skip first char (it can be /) - for (i = 1; dir[i]; i++) { - int ret; + // mkdir -p one/two/three is not an error if the path already exists, + // but is if "three" is a file. The others we dereference and catch + // not-a-directory along the way, but the last one we must explicitly + // test for. Might as well do it up front. + + if (!stat(dir, &buf) && !S_ISDIR(buf.st_mode)) { + errno = EEXIST; + return 1; + } - if (dir[i] != '/') continue; - dir[i] = 0; - ret = mkdir(dir, TT.mode); - if (ret < 0 && errno != EEXIST) return ret; - dir[i] = '/'; - } + for (s=dir; ; s++) { + char save=0; + + // Skip leading / of absolute paths. + if (s!=dir && *s == '/' && toys.optflags) { + save = *s; + *s = 0; + } else if (*s) continue; + + if (mkdir(dir, TT.mode)<0 && (!toys.optflags || errno != EEXIST)) + return 1; + + if (!(*s = save)) break; } - return mkdir(dir, TT.mode); + + return 0; } void mkdir_main(void)