On this page:
get-ext
has-ext?
remove-ext
remove-ext*
add-ext
get-enclosing-dir
6.0.1.13

5 File

 (require sugar/file) package: sugar

File utilities, mostly in the realm of file extensions. These functions don’t access the filesystem.

Arguments that are pathish? can take either a string or a path. For clarity below, I’ve used strings.

procedure

(get-ext file-path)  (or/c #f string?)

  file-path : pathish?
Return the last file extension of file-path as a string, or #f if it has no extension. Omit the intervening . separator.

Examples:

> (get-ext "foo.txt")

"txt"

> (get-ext "/path/to/foo.txt")

"txt"

> (get-ext "/path/to/foo.txt.bar")

"bar"

> (get-ext "/path/to/file-without-extension")

#f

> (get-ext "/path/to/directory/")

#f

procedure

(has-ext? file-path ext)  boolean?

  file-path : pathish?
  ext : stringish?
Return #t if the last file extension of file-path is ext, otherwise #f.

Examples:

> (has-ext? "foo.txt" "txt")

#t

> (has-ext? "foo.txt" "jpg")

#f

> (has-ext? "foo.jpg.txt" "jpg")

#f

procedure

(remove-ext file-path)  path?

  file-path : pathish?
Remove the last file extension of file-path, and return the path that remains. If file-path has no extension, you just get the same file-path. Does not use the filesystem.

Examples:

> (remove-ext "foo.txt")

#<path:foo>

> (remove-ext "/path/to/foo.txt")

#<path:/path/to/foo>

> (remove-ext "/path/to/foo.txt.bar")

#<path:/path/to/foo.txt>

> (remove-ext (remove-ext "/path/to/foo.txt.bar"))

#<path:/path/to/foo>

procedure

(remove-ext* file-path)  path?

  file-path : pathish?
Like remove-ext, just more. Remove all file extensions from file-path, and return the path that remains. If file-path has no extensions, you just get the same file-path. Does not use the filesystem.

Examples:

> (remove-ext* "foo.txt")

#<path:foo>

> (remove-ext* "/path/to/foo.txt")

#<path:/path/to/foo>

> (remove-ext* "/path/to/foo.txt.bar")

#<path:/path/to/foo>

> (remove-ext* (remove-ext* "/path/to/foo.txt.bar"))

#<path:/path/to/foo>

procedure

(add-ext file-path ext)  path?

  file-path : pathish?
  ext : stringish?
Return a new file-path with ext appended. Note that this does not replace an existing file extension. If that’s what you want, then do (add-ext (remove-ext file-path) ext).

Examples:

> (add-ext "foo" "txt")

#<path:foo.txt>

> (add-ext "foo.txt" "jpg")

#<path:foo.txt.jpg>

> (add-ext (remove-ext "foo.txt") "jpg")

#<path:foo.jpg>

procedure

(get-enclosing-dir path)  path?

  path : pathish?
Return the enclosing directory of path. Does not consult the filesystem about whether path is valid. If you reach the root directory, then (get-enclosing-dir root) will just return root again.

Examples:

> (define bin (string->path "/usr/bin"))
> bin

#<path:/usr/bin>

> (get-enclosing-dir bin)

#<path:/usr/>

> (get-enclosing-dir (get-enclosing-dir bin))

#<path:/>

> (get-enclosing-dir (get-enclosing-dir (get-enclosing-dir bin)))

#<path:/>