Does too much for the use case at hand. It creates all directory
segments. I only want to create one directory. You see the
difference between the two also in the JavaScript API:
fs.mkdirSync(path[, options])
recursive Default: false
https://nodejs.org/api/fs.html
In JavaScript its just one API with a recursive option. But
they retain the usual operating system semantics when recursive=false
,
that it will also bark when the directory already exists.
A predicate that creates only one directory segment on demand
does not exist, because make_directory_path/1 does too much,
and make_directory/1 does too less. So you have to bootstrap it.
ensure_directory/1
is more defensive than make_directory_path/1.
Its safer for scripting. If you have an errorneaous path in make_directory_path/1
it will arbitarily write into your harddisk, since make_directory_path/1
might create the path against your intention. For ensure_directory/1
you have the requirement that the parent directory already existing.
But its not meant to be used in a parallel multi-user environment for shared
directories, its not a concurrent use case that I have.
Edit 19.11.2023
Or with user interaction, again recursive=false
and nothing parallel:
/* assumption, parent already exists */
ensure_directory_interactive(F) :-
\+ file_exists(F), !,
ask('Directory does not yet exist, do you want to create it?', y),
make_directory(F).
ensure_directory_interactive(F) :-
\+ file_property(F, type(directory)), !,
prompt('Cannot create directory, already other file at location.'), fail.
ensure_directory_interactive(_).
If file_exists/1
has wrong semantics, the above script doesn’t work
correctly. I also tend now that it should not follow links, and fail if a link
is broken. But for user interaction, and when its an important path in
script, I would indeed rather use make_directory_path/1. ensure_directory/1
is
more conceived for automation, when the important paths already exist and
you want to overwrite and/or create some content. Since its more defensive
it prevents errorneous overwrite. Also an interactive script might want to also
check access rights and give the end-user some hints, what do to or guide it
through more stuff. Thats also not covered by file_exists/1.