Skip to content

Commit

Permalink
Improve directory changing
Browse files Browse the repository at this point in the history
Rename cd to chdir. Add with-save-directory and with-chdir. Make
getcwd setf-able.
  • Loading branch information
ruricolist committed Dec 31, 2024
1 parent 894bba3 commit 3e4ed59
Showing 1 changed file with 41 additions and 6 deletions.
47 changes: 41 additions & 6 deletions os.lisp
Original file line number Diff line number Diff line change
Expand Up @@ -9,19 +9,31 @@
(:import-from :cmd)
(:import-from :kiln/dispatch :exec :exit)
(:import-from :kiln/flags :dbg)
(:import-from :uiop :getenv :getenvp :hostname)
;; TODO Remove when Quicklisp updates
(:shadow :parse-cmd-dsl)
(:import-from
:uiop
:file-exists-p
:directory-exists-p
:getenv
:getenvp
:hostname)
(:shadow
;; TODO Remove when Quicklisp updates
:parse-cmd-dsl)
(:export
:cd
:chdir
:directory-exists-p
:exec
:exit
:file-exists-p
:getcwd
:getenv
:getenvp
:getpid
:hostname
:os-linux-p
:setpgrp))
:setpgrp
:with-chdir
:with-save-directory))
(in-package :kiln/os)

#.(if (uiop:os-unix-p)
Expand All @@ -35,13 +47,36 @@
(setf (documentation #'setpgrp 'function)
"Make this process the leader of a new process group.")

(defun cd (&optional (dir (user-homedir-pathname)))
(defun chdir (&optional (dir (user-homedir-pathname)))
"Set the operating system directory and sync
`*default-pathname-defaults*' to it."
(let ((dir (cmd::resolve-dir dir)))
(uiop:chdir dir)
(setf *default-pathname-defaults* dir)))

(defun getcwd ()
(uiop:getcwd))

(defun (setf getcwd) (dir)
(chdir dir))

(defun call/save-directory (fn)
(let ((start-dir (uiop:getcwd)))
(unwind-protect
(funcall fn)
(chdir start-dir))))

(defmacro with-save-directory ((&key) &body body)
"Run BODY, restoring the current directory afterwards."
(with-thunk (body)
`(call/save-directory ,body)))

(defmacro with-chdir ((dir) &body body)
"Set current directory to DIR, run BODY, restore current directory."
`(with-save-directory ()
(chdir ,dir)
,@body))

(cffi:defcfun (%execv "execv") :int
(path :string)
(args (:pointer :string)))
Expand Down

0 comments on commit 3e4ed59

Please sign in to comment.