Leif Andersen
Leif Andersen

Reputation: 22342

Ensure that a path is a directory path in Racket

Racket's path library treats files and directories a little differently. In Unix based Racket distributions, directories have a trailing / at the end. Several functions, such as in-directory and path-only will use this information to treat paths leading to files and directories differently.

Unfortunately, the recommended way to create a path, build-path does not have any good mechanism for creating a directory path. I know I could make a path as a string and use string->path, but that is going to be more brittle than using build-path directly:

> (string->path "a/b/")
#<path:a/b/>

Another thing I could do is combine build-path and path-only to add an extra 'trash' element to the path, which then gets stripped. But this is clunky as I then have to make that 'trash' string.

> (path-only (build-path "a" "b" "trash"))
#<path:a/b/>

I 'could' just put a . (or 'same) in the build-path function, which ensures that its a directory path, but then the path itself has a . at the end, which can't even be removed with path-only:

> (build-path "a" "b" 'same)
#<path:a/b/.>

While all three of these can turn a path into a directory path, is there any cleaner way to turn an existing Racket path into a directory path?

Upvotes: 2

Views: 339

Answers (1)

Leif Andersen
Leif Andersen

Reputation: 22342

You are on the right track by using build-path. The function you are looking for is path->directory-path. It takes a path object, and turns it into a directory path (in unix this means adding the trailing / you mentioned.

> (build-path "a" "b")
#<path:a/b>
> (path->directory-path (build-path "a" "b"))
#<path:a/b/>

Upvotes: 1

Related Questions