Blame support/xmkdirp.c

Packit Bot 3f3af5
/* Error-checking replacement for "mkdir -p".
Packit Bot 3f3af5
   Copyright (C) 2018 Free Software Foundation, Inc.
Packit Bot 3f3af5
   This file is part of the GNU C Library.
Packit Bot 3f3af5
Packit Bot 3f3af5
   The GNU C Library is free software; you can redistribute it and/or
Packit Bot 3f3af5
   modify it under the terms of the GNU Lesser General Public
Packit Bot 3f3af5
   License as published by the Free Software Foundation; either
Packit Bot 3f3af5
   version 2.1 of the License, or (at your option) any later version.
Packit Bot 3f3af5
Packit Bot 3f3af5
   The GNU C Library is distributed in the hope that it will be useful,
Packit Bot 3f3af5
   but WITHOUT ANY WARRANTY; without even the implied warranty of
Packit Bot 3f3af5
   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
Packit Bot 3f3af5
   Lesser General Public License for more details.
Packit Bot 3f3af5
Packit Bot 3f3af5
   You should have received a copy of the GNU Lesser General Public
Packit Bot 3f3af5
   License along with the GNU C Library; if not, see
Packit Bot 3f3af5
   <http://www.gnu.org/licenses/>.  */
Packit Bot 3f3af5
Packit Bot 3f3af5
#include <support/support.h>
Packit Bot 3f3af5
#include <support/check.h>
Packit Bot 3f3af5
#include <support/xunistd.h>
Packit Bot 3f3af5
Packit Bot 3f3af5
#include <stdlib.h>
Packit Bot 3f3af5
#include <string.h>
Packit Bot 3f3af5
#include <errno.h>
Packit Bot 3f3af5
Packit Bot 3f3af5
/* Equivalent of "mkdir -p".  Any failures cause FAIL_EXIT1 so no
Packit Bot 3f3af5
   return code is needed.  */
Packit Bot 3f3af5
Packit Bot 3f3af5
void
Packit Bot 3f3af5
xmkdirp (const char *path, mode_t mode)
Packit Bot 3f3af5
{
Packit Bot 3f3af5
  struct stat s;
Packit Bot 3f3af5
  const char *slash_p;
Packit Bot 3f3af5
  int rv;
Packit Bot 3f3af5
Packit Bot 3f3af5
  if (path[0] == 0)
Packit Bot 3f3af5
    return;
Packit Bot 3f3af5
Packit Bot 3f3af5
  if (stat (path, &s) == 0)
Packit Bot 3f3af5
    {
Packit Bot 3f3af5
      if (S_ISDIR (s.st_mode))
Packit Bot 3f3af5
	return;
Packit Bot 3f3af5
      errno = EEXIST;
Packit Bot 3f3af5
      FAIL_EXIT1 ("mkdir_p (\"%s\", 0%o): %m", path, mode);
Packit Bot 3f3af5
    }
Packit Bot 3f3af5
Packit Bot 3f3af5
  slash_p = strrchr (path, '/');
Packit Bot 3f3af5
  if (slash_p != NULL)
Packit Bot 3f3af5
    {
Packit Bot 3f3af5
      while (slash_p > path && slash_p[-1] == '/')
Packit Bot 3f3af5
	--slash_p;
Packit Bot 3f3af5
      if (slash_p > path)
Packit Bot 3f3af5
	{
Packit Bot 3f3af5
	  char *parent = xstrndup (path, slash_p - path);
Packit Bot 3f3af5
	  xmkdirp (parent, mode);
Packit Bot 3f3af5
	  free (parent);
Packit Bot 3f3af5
	}
Packit Bot 3f3af5
    }
Packit Bot 3f3af5
Packit Bot 3f3af5
  rv = mkdir (path, mode);
Packit Bot 3f3af5
  if (rv != 0)
Packit Bot 3f3af5
    FAIL_EXIT1 ("mkdir_p (\"%s\", 0%o): %m", path, mode);
Packit Bot 3f3af5
Packit Bot 3f3af5
  return;
Packit Bot 3f3af5
}