
:- ensure_loaded(common).
cvs_id('$Id: mkdir.pl,v 1.5 2004/09/01 19:55:03 sandro Exp $').

:- debug(mkdir). 

%debug(_, F, A) :-
%	format(user_error, F, A), nl.

%  Like open/4, but creates parent directories if necessary
%  (very low overhead if not necessary)
%
open_p(File, Mode, Stream, Options) :-
	catch(open(File, Mode, Stream, Options),
	      error(existence_error(source_sink, File), context(_, 'No such file or directory')),
	      (   make_parent_directories_if_missing(File),
		  open(File, Mode, Stream, Options)
	      )
	     ).

					   
make_parent_directories_if_missing(Dir) :-
	atom(Dir),
	%debug(mkdir, 'Make parents of ~q', [Dir]),
	concat_atom(Parts, '/', Dir),
	make_parent_directories_if_missing('', Parts).

/* or...!
          chop at last slash
          if dir exists, return, else [call parent], mkdir
   */
   
% first arg is an atom /foo/bar/baz which we know is fine
% second are is a list of dirs we're not sure about
make_parent_directories_if_missing(_Known, [_H]).
	
make_parent_directories_if_missing(Known, [H|T]) :-
	%debug(mkdir, 'Given ~q, mkdir ~q', [Known, [H|T]]),
	(   Known = '/'
	->  concat_atom([Known, H], Here)
        ;   concat_atom([Known, '/', H], Here)
	),
	(   exists_directory(Here)
	->  true%,
	    %debug(mkdir, 'exists dir ~q', [Here])
	;   debug(mkdir, 'creating missing parent dir ~w', [Here]),
	    make_directory(Here)%,
	    %debug(mkdir, 'made dir ~q', [Here])
	),
	make_parent_directories_if_missing(Here, T).

mkdir(Dir) :-
	(   exists_directory(Dir)
	->  true
	;   make_parent_directories_if_missing(Dir),
	    make_directory(Dir)
	).

