Skip to content

Commit

Permalink
Merge pull request #713 from vyzo/mktemp
Browse files Browse the repository at this point in the history
Some utilities for working with temporary files
  • Loading branch information
vyzo authored Jul 3, 2023
2 parents 113bb39 + ef6df89 commit 25938b1
Show file tree
Hide file tree
Showing 4 changed files with 58 additions and 0 deletions.
27 changes: 27 additions & 0 deletions doc/reference/os.md
Original file line number Diff line number Diff line change
Expand Up @@ -481,3 +481,30 @@ Please document me!
:::

Please document me!

## Temporary Files
::: tip To use bindings from this module
```scheme
(import :std/os/temporaries)
```
:::

### make-temporary-file-name
```scheme
(make-temporary-file-name name) -> string
name := string; prefix of temporary filename in /tmp
```

Creates a new temporary file name in /tmp and with name prefix `name`.
It makes `mktemp` sane by appending the current timestamp in nanosecods.

### call-with-temporary-file-name
```scheme
(call-with-temporary-file-name name fun) -> any
name := string; prefix of temporary filename in /tmp
fun := lambda (string) -> any
```

Creates a temporary filename and invokes `fun` with it, deleting the
temporary file on unwind if it has been created.
3 changes: 3 additions & 0 deletions src/std/build-deps
Original file line number Diff line number Diff line change
Expand Up @@ -590,6 +590,9 @@
std/os/signalfd
std/sugar))
(std/os/pid "os/pid" (gerbil/core std/foreign))
(std/os/temporaries
"os/temporaries"
(gerbil/core gerbil/gambit/os std/foreign std/sugar))
(std/net/bio/file
"net/bio/file"
(gerbil/core
Expand Down
1 change: 1 addition & 0 deletions src/std/build-spec.ss
Original file line number Diff line number Diff line change
Expand Up @@ -187,6 +187,7 @@
(else '()))
"os/signal-handler"
"os/pid"
"os/temporaries"
;; :std/net/bio
"net/bio/input"
"net/bio/output"
Expand Down
27 changes: 27 additions & 0 deletions src/std/os/temporaries.ss
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
;;; -*- Gerbil -*-
;;; © vyzo
;;; [incomplete] OS temporary file interface

(import :gerbil/gambit/os
:std/foreign
:std/sugar)
(export make-temporary-file-name
call-with-temporary-file-name)

(def (call-with-temporary-file-name name fun)
(def tmp (make-temporary-file-name name))
(try
(fun tmp)
(finally
(when (file-exists? tmp)
(delete-file tmp)))))

(def (make-temporary-file-name name)
(let (tmp (mktemp (string-append "/tmp/" name ".XXXXXX")))
(when (string-empty? tmp)
(error "Cannot create temporary file" name))
(string-append tmp "." (number->string (time->seconds (current-time))))))

(begin-ffi (mktemp)
(c-declare "#include <stdlib.h>")
(define-c-lambda mktemp (char-string) char-string))

0 comments on commit 25938b1

Please sign in to comment.