Page 1 of 1

make-dirs

Posted: Mon Aug 14, 2006 10:31 am
by tom
how can I make a directory that includes subdirectories however many levels deep?

Posted: Mon Aug 14, 2006 12:18 pm
by Lutz
like this:

Code: Select all

> (make-dir "one")
true
> (make-dir "one/two")
true
> (make-dir "one/two/three")
true
> 
Lutz

Posted: Mon Aug 14, 2006 12:45 pm
by tom
I'm sorry, I meant all at once, something analogous to

Code: Select all

 $ mkdir -p one/two/three 
...something that makes the deepest subdirectory and
all its parents whether or not the parent existed
previously.

Posted: Mon Aug 14, 2006 12:57 pm
by Lutz
this will work:

Code: Select all

(exec "mkdir -p one/two/three")
Lutz

Posted: Mon Aug 14, 2006 1:32 pm
by tom
thanks.

That's sort of cheating, though!

:-)

Posted: Mon Aug 14, 2006 2:09 pm
by Lutz
That's sort of cheating, though!
shhh, don't let anybody know, and here is the pure and portable thing:

Code: Select all

(define (makedir path)
  (let (old-path (real-path))
        (dolist (p (parse path "/"))
                (make-dir p)
                (change-dir p))
        (change-dir old-path)))

(makedir "one/two/three")
Lutz

Posted: Tue Aug 15, 2006 3:47 pm
by tom
hi Lutz,

hmm. the "correct" version doesn't seem to work today. For now, I
commented out your function, and am using the "cheating" method.

I'll go ahead and post my whole complex, lengthy, and guru-like script
(which will also change the way we use our computers forever). Here
it is:

Code: Select all

#!/usr/bin/newlisp

;; newlisp implementation of "mkdir -p" (thanks Lutz!)

; (define (make-sub-dirs path)
;   (let (old-path (real-path))
;         (dolist (p (parse path "/"))
;                 (make-dir p)
;                 (change-dir p))
;         (change-dir old-path))) 

;; split up the date

(set  
 'the-year (date (date-value) 0 "%Y")
 'the-month (date (date-value) 0 "%b")
 'the-day (date (date-value) 0 "%d")
 'the-time (date (date-value) 0 "%H:%M:%S") 
 )

;; create directories, subdirectories, file name

(set
'base-dir-path "/path/to/dir"
'text-dir-path 
	 (append base-dir-path "/" the-year "/" the-month "/" the-day"/")
'file-name 
	(append (date (date-value) 0 "%H%M%S")".txt")	 
	 )

;(make-sub-dirs text-dir-path)

(exec (append "mkdir -p " text-dir-path))

;; write stuff to file

(device (open (append text-dir-path file-name) "write"))
(print "-*- Outline -*-\n\n")
(print (append "* " (string (date)) "\n\n"))
(close (device))

;; launch editor with file

(! (append "gnuclient " (append text-dir-path file-name)))

;; quit :-)

;(exit)


Posted: Tue Aug 15, 2006 7:56 pm
by Dmi
The other simple native version

Code: Select all

(define (mkdirs path , p)
  (dolist (l (parse path "/"))
    (push l p -1)
    (unless (empty? l) (make-dir (join p "/")))))
example: (mkdirs "the/test/dir") or (mkdirs "/the/test/dir")
this one even returns nil on error :-)
...just a coding exercise