Search code examples
schemeguile

How do I open a file relative to the source files directory in Guile Scheme?


I'm writing a Guix developer environment definition for a Python project I'm working on, it looks something like this:

(use-modules (gnu packages)
             (gnu packages python)
             (gnu packages python-crypto)
             (gnu packages python-web)
             (gnu packages python-xyz)
             (ice-9 rdelim)
             ((guix licenses) #:prefix license:)
             (guix build-system python)
             (guix download)
             (guix packages))

(define (requirements-file->guix-packages filename)
  (let* ((requirements-text (with-input-from-file filename read-string))
         (requirements-list (string-split requirements-text #\newline)))
    (map (lambda (requirement)
           (specification->package (string-append "python-" requirement)))
         requirements-list)))

(define internsidor-deps      (requirements-file->guix-packages "requirements.in"))
(define development-tools     (list python-pip python-wrapper python-virtualenv python-jedi))

(append internsidor-deps development-tools)

Now this piece of code works fine if evaluated while standing at the root of the project folder, where the requirements.in and requirements-prod.in resides. But if the user moves to a subfolder and runs the code like

guix environment --ad-hoc --load='../development-environment.scm'

they will find themselves with the following error

guix environment: error: while evaluating '../development-environment.scm', it failed opening 'requirements.in' with the error: No such file or directory

(or an error along those lines, I've modified my Guix to provide a better error message for this failure.)

So my question is then: How can I modify the call to with-input-from-file so that the path is relative to the Scheme file rather than to the $PWD of the shell?


Solution

  • You can use (dirname (current-filename)) to get the directory of the current file. See also https://www.gnu.org/software/guile/manual/guile.html#Source-Properties