1 ;;; GNU Guix --- Functional package management for GNU
2 ;;; Copyright © 2012, 2013, 2014, 2015, 2016, 2017, 2018, 2019, 2020, 2021 Ludovic Courtès <ludo@gnu.org>
3 ;;; Copyright © 2013, 2014, 2015 Mark H Weaver <mhw@netris.org>
4 ;;; Copyright © 2014 Eric Bavier <bavier@member.fsf.org>
5 ;;; Copyright © 2014 Ian Denhardt <ian@zenhack.net>
6 ;;; Copyright © 2016 Mathieu Lirzin <mthl@gnu.org>
7 ;;; Copyright © 2015 David Thompson <davet@gnu.org>
8 ;;; Copyright © 2017 Mathieu Othacehe <m.othacehe@gmail.com>
9 ;;; Copyright © 2018, 2020 Marius Bakke <marius@gnu.org>
10 ;;; Copyright © 2020 Efraim Flashner <efraim@flashner.co.il>
11 ;;; Copyright © 2021 Simon Tournier <zimon.toutoune@gmail.com>
12 ;;; Copyright © 2021 Chris Marusich <cmmarusich@gmail.com>
14 ;;; This file is part of GNU Guix.
16 ;;; GNU Guix is free software; you can redistribute it and/or modify it
17 ;;; under the terms of the GNU General Public License as published by
18 ;;; the Free Software Foundation; either version 3 of the License, or (at
19 ;;; your option) any later version.
21 ;;; GNU Guix is distributed in the hope that it will be useful, but
22 ;;; WITHOUT ANY WARRANTY; without even the implied warranty of
23 ;;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
24 ;;; GNU General Public License for more details.
26 ;;; You should have received a copy of the GNU General Public License
27 ;;; along with GNU Guix. If not, see <http://www.gnu.org/licenses/>.
29 (define-module (guix utils)
30 #:use-module (guix config)
31 #:use-module (srfi srfi-1)
32 #:use-module (srfi srfi-9)
33 #:use-module (srfi srfi-11)
34 #:use-module (srfi srfi-26)
35 #:use-module (srfi srfi-39)
36 #:use-module (ice-9 ftw)
37 #:use-module (rnrs io ports) ;need 'port-position' etc.
38 #:use-module ((rnrs bytevectors) #:select (bytevector-u8-set!))
39 #:use-module (guix memoization)
40 #:use-module ((guix build utils) #:select (dump-port mkdir-p delete-file-recursively))
41 #:use-module ((guix build syscalls) #:select (mkdtemp! fdatasync))
42 #:use-module ((guix combinators) #:select (fold2))
43 #:use-module (guix diagnostics) ;<location>, &error-location, etc.
44 #:use-module (ice-9 format)
45 #:use-module (ice-9 regex)
46 #:use-module (ice-9 match)
47 #:use-module (ice-9 format)
48 #:use-module ((ice-9 iconv) #:prefix iconv:)
49 #:autoload (zlib) (make-zlib-input-port make-zlib-output-port)
50 #:use-module (system foreign)
51 #:re-export (<location> ;for backwards compatibility
57 source-properties->location
58 location->source-properties
67 #:export (strip-keyword-arguments
68 default-keyword-arguments
69 substitute-keyword-arguments
70 ensure-keyword-arguments
72 current-source-directory
74 nix-system->gnu-triplet
75 gnu-triplet->nix-system
77 %current-target-system
78 package-name->name+version
93 version-major+minor+point
99 string-replace-substring
102 tarball-sans-extension
105 call-with-temporary-output-file
106 call-with-temporary-directory
107 with-atomic-file-output
109 with-environment-variables
110 arguments-from-environment-variable
120 call-with-decompressed-port
121 compressed-output-port
122 call-with-compressed-output-port
123 canonical-newline-port
130 ;;; Environment variables.
133 (define (call-with-environment-variables variables thunk)
134 "Call THUNK with the environment VARIABLES set."
135 (let ((environment (environ)))
138 (for-each (match-lambda
140 (setenv variable value)))
144 (environ environment)))))
146 (define-syntax-rule (with-environment-variables variables exp ...)
147 "Evaluate EXP with the given environment VARIABLES set."
148 (call-with-environment-variables variables
149 (lambda () exp ...)))
151 (define (arguments-from-environment-variable variable)
152 "Retrieve value of environment variable denoted by string VARIABLE in the
153 form of a list of strings (`char-set:graphic' tokens) suitable for consumption
154 by `args-fold', if VARIABLE is defined, otherwise return an empty list."
155 (let ((env (getenv variable)))
157 (string-tokenize env char-set:graphic)
162 ;;; Filtering & pipes.
165 (define (filtered-port command input)
166 "Return an input port where data drained from INPUT is filtered through
167 COMMAND (a list). In addition, return a list of PIDs that the caller must
168 wait. When INPUT is a file port, it must be unbuffered; otherwise, any
169 buffered data is lost."
170 (let loop ((input input)
172 (if (file-port? input)
175 (match (primitive-fork)
181 (close-port (current-input-port))
182 (dup2 (fileno input) 0)
183 (close-port (current-output-port))
184 (dup2 (fileno out) 1)
187 (apply execl (car command) command))
189 (format (current-error-port)
190 "filtered-port: failed to execute '~{~a ~}': ~a~%"
191 command (strerror (system-error-errno args))))))
193 (primitive-_exit 1))))
196 (values in (cons child pids))))))
198 ;; INPUT is not a file port, so fork just for the sake of tunneling it
199 ;; through a file port.
202 (match (primitive-fork)
208 (dump-port input out))
211 (false-if-exception (close out))
212 (primitive-_exit 0))))
216 (loop in (cons child pids)))))))))
218 (define (lzip-port proc port . args)
219 "Return the lzip port produced by calling PROC (a symbol) on PORT and ARGS.
220 Raise an error if lzlib support is missing."
221 (let ((make-port (module-ref (resolve-interface '(lzlib)) proc)))
224 (define (zstd-port proc port . args)
225 "Return the zstd port produced by calling PROC (a symbol) on PORT and ARGS.
226 Raise an error if zstd support is missing."
227 (let ((make-port (module-ref (resolve-interface '(zstd)) proc)))
230 (define (decompressed-port compression input)
231 "Return an input port where INPUT is decompressed according to COMPRESSION,
232 a symbol such as 'xz."
234 ((or #f 'none) (values input '()))
235 ('bzip2 (filtered-port `(,%bzip2 "-dc") input))
236 ('xz (filtered-port `(,%xz "-dc") input))
237 ('gzip (values (make-zlib-input-port input #:format 'gzip)
239 ('lzip (values (lzip-port 'make-lzip-input-port input)
241 ('zstd (values (zstd-port 'make-zstd-input-port input)
243 (_ (error "unsupported compression scheme" compression))))
245 (define (call-with-decompressed-port compression port proc)
246 "Call PROC with a wrapper around PORT, a file port, that decompresses data
247 read from PORT according to COMPRESSION, a symbol such as 'xz."
248 (let-values (((decompressed pids)
249 (decompressed-port compression port)))
255 (close-port decompressed)
256 (unless (every (compose zero? cdr waitpid) pids)
257 (error "decompressed-port failure" pids))))))
259 (define (filtered-output-port command output)
260 "Return an output port. Data written to that port is filtered through
261 COMMAND and written to OUTPUT, an output file port. In addition, return a
262 list of PIDs to wait for. OUTPUT must be unbuffered; otherwise, any buffered
266 (match (primitive-fork)
272 (close-port (current-input-port))
274 (close-port (current-output-port))
275 (dup2 (fileno output) 1)
278 (apply execl (car command) command))
280 (format (current-error-port)
281 "filtered-output-port: failed to execute '~{~a ~}': ~a~%"
282 command (strerror (system-error-errno args))))))
284 (primitive-_exit 1))))
287 (values out (list child)))))))
289 (define* (compressed-output-port compression output
291 "Return an output port whose input is compressed according to COMPRESSION,
292 a symbol such as 'xz, and then written to OUTPUT. In addition return a list
293 of PIDs to wait for. OPTIONS is a list of strings passed to the compression
294 program--e.g., '(\"--fast\")."
296 ((or #f 'none) (values output '()))
297 ('bzip2 (filtered-output-port `(,%bzip2 "-c" ,@options) output))
298 ('xz (filtered-output-port `(,%xz "-c" ,@options) output))
299 ('gzip (values (make-zlib-output-port output #:format 'gzip)
301 ('lzip (values (lzip-port 'make-lzip-output-port output)
303 ('zstd (values (zstd-port 'make-zstd-output-port output)
305 (_ (error "unsupported compression scheme" compression))))
307 (define* (call-with-compressed-output-port compression port proc
309 "Call PROC with a wrapper around PORT, a file port, that compresses data
310 that goes to PORT according to COMPRESSION, a symbol such as 'xz. OPTIONS is
311 a list of command-line arguments passed to the compression program."
312 (let-values (((compressed pids)
313 (compressed-output-port compression port
320 (close-port compressed)
321 (unless (every (compose zero? cdr waitpid) pids)
322 (error "compressed-output-port failure" pids))))))
324 (define* (edit-expression source-properties proc #:key (encoding "UTF-8"))
325 "Edit the expression specified by SOURCE-PROPERTIES using PROC, which should
326 be a procedure that takes the original expression in string and returns a new
327 one. ENCODING will be used to interpret all port I/O, it default to UTF-8.
328 This procedure returns #t on success."
329 (with-fluids ((%default-port-encoding encoding))
330 (let* ((file (assq-ref source-properties 'filename))
331 (line (assq-ref source-properties 'line))
332 (column (assq-ref source-properties 'column))
333 (in (open-input-file file))
334 ;; The start byte position of the expression.
335 (start (begin (while (not (and (= line (port-line in))
336 (= column (port-column in))))
337 (when (eof-object? (read-char in))
338 (error (format #f "~a: end of file~%" in))))
340 ;; The end byte position of the expression.
341 (end (begin (read in) (ftell in))))
342 (seek in 0 SEEK_SET) ; read from the beginning of the file.
343 (let* ((pre-bv (get-bytevector-n in start))
344 ;; The expression in string form.
345 (str (iconv:bytevector->string
346 (get-bytevector-n in (- end start))
348 (post-bv (get-bytevector-all in))
350 ;; Verify the edited expression is still a scheme expression.
351 (call-with-input-string str* read)
352 ;; Update the file with edited expression.
353 (with-atomic-file-output file
355 (put-bytevector out pre-bv)
357 ;; post-bv maybe the end-of-file object.
358 (when (not (eof-object? post-bv))
359 (put-bytevector out post-bv))
364 ;;; Keyword arguments.
367 (define (strip-keyword-arguments keywords args)
368 "Remove all of the keyword arguments listed in KEYWORDS from ARGS."
369 (let loop ((args args)
374 (((? keyword? kw) arg . rest)
376 (if (memq kw keywords)
378 (cons* arg kw result))))
380 (loop tail (cons head result))))))
382 (define (default-keyword-arguments args defaults)
383 "Return ARGS augmented with any keyword/value from DEFAULTS for
384 keywords not already present in ARGS."
385 (let loop ((defaults defaults)
392 (cons* kw value args))))
396 (define-syntax collect-default-args
401 (collect-default-args rest ...))
402 ((_ (kw _ dflt) rest ...)
403 (cons* kw dflt (collect-default-args rest ...)))))
405 (define-syntax substitute-keyword-arguments
407 "Return a new list of arguments where the value for keyword arg KW is
408 replaced by EXP. EXP is evaluated in a context where VAR is bound to the
409 previous value of the keyword argument, or DFLT if given."
410 ((_ original-args ((kw var dflt ...) exp) ...)
411 (let loop ((args (default-keyword-arguments
413 (collect-default-args (kw var dflt ...) ...)))
416 ((kw var rest (... ...))
417 (loop rest (cons* exp kw before)))
420 (loop rest (cons x before)))
422 (reverse before)))))))
424 (define (delkw kw lst)
425 "Remove KW and its associated value from LST, a keyword/value list such
426 as '(#:foo 1 #:bar 2)."
432 ((kw? value rest ...)
434 (append (reverse result) rest)
435 (loop rest (cons* value kw? result)))))))
437 (define (ensure-keyword-arguments args kw/values)
438 "Force the keywords arguments KW/VALUES in the keyword argument list ARGS.
441 (ensure-keyword-arguments '(#:foo 2) '(#:foo 2))
444 (ensure-keyword-arguments '(#:foo 2) '(#:bar 3))
447 (ensure-keyword-arguments '(#:foo 2) '(#:bar 3 #:foo 42))
448 => (#:foo 42 #:bar 3)
450 (let loop ((args args)
451 (kw/values kw/values)
455 (append (reverse result) kw/values))
457 (match (memq kw kw/values)
459 (loop rest (delkw kw kw/values) (cons* value kw result)))
461 (loop rest kw/values (cons* value kw result))))))))
468 (define* (nix-system->gnu-triplet
469 #:optional (system (%current-system)) (vendor "unknown"))
470 "Return a guess of the GNU triplet corresponding to Nix system
474 (string-append "arm-" vendor "-linux-gnueabihf"))
476 (let* ((dash (string-index system #\-))
477 (arch (substring system 0 dash))
478 (os (substring system (+ 1 dash))))
481 (if (string=? os "linux")
485 (define (gnu-triplet->nix-system triplet)
486 "Return the Nix system type corresponding to TRIPLET, a GNU triplet as
487 returned by `config.guess'."
488 (let ((triplet (cond ((string-match "^i[345]86-(.*)$" triplet)
491 (string-append "i686-" (match:substring m 1))))
493 (cond ((string-match "^arm[^-]*-([^-]+-)?linux-gnueabihf" triplet)
495 ((string-match "^([^-]+)-([^-]+-)?linux-gnu.*" triplet)
498 ;; Nix omits `-gnu' for GNU/Linux.
499 (string-append (match:substring m 1) "-linux")))
500 ((string-match "^([^-]+)-([^-]+-)?([[:alpha:]]+)([0-9]+\\.?)*$" triplet)
503 ;; Nix strip the version number from names such as `gnu0.3',
504 ;; `darwin10.2.0', etc., and always strips the vendor part.
505 (string-append (match:substring m 1) "-"
506 (match:substring m 3))))
509 (define %current-system
510 ;; System type as expected by Nix, usually ARCHITECTURE-KERNEL.
511 ;; By default, this is equal to (gnu-triplet->nix-system %host-type).
512 (make-parameter %system))
514 (define %current-target-system
515 ;; Either #f or a GNU triplet representing the target system we are
516 ;; cross-building to.
519 (define* (package-name->name+version spec
520 #:optional (delimiter #\@))
521 "Given SPEC, a package name like \"foo@0.9.1b\", return two values: \"foo\"
522 and \"0.9.1b\". When the version part is unavailable, SPEC and #f are
523 returned. Both parts must not contain any '@'. Optionally, DELIMITER can be
524 a character other than '@'."
525 (match (string-rindex spec delimiter)
526 (#f (values spec #f))
527 (idx (values (substring spec 0 idx)
528 (substring spec (1+ idx))))))
530 (define* (target-mingw? #:optional (target (%current-target-system)))
532 (string-suffix? "-mingw32" target)))
534 (define* (target-arm32? #:optional (target (or (%current-target-system)
536 (string-prefix? "arm" target))
538 (define* (target-aarch64? #:optional (target (or (%current-target-system)
540 (string-prefix? "aarch64" target))
542 (define* (target-arm? #:optional (target (or (%current-target-system)
544 (or (target-arm32? target) (target-aarch64? target)))
546 (define* (target-powerpc? #:optional (target (or (%current-target-system)
548 (string-prefix? "powerpc" target))
550 (define* (target-64bit? #:optional (system (or (%current-target-system)
552 (any (cut string-prefix? <> system) '("x86_64" "aarch64" "mips64" "powerpc64")))
554 (define* (cc-for-target #:optional (target (%current-target-system)))
556 (string-append target "-gcc")
559 (define* (cxx-for-target #:optional (target (%current-target-system)))
561 (string-append target "-g++")
564 (define* (pkg-config-for-target #:optional (target (%current-target-system)))
566 (string-append target "-pkg-config")
569 (define version-compare
571 (let ((sym (or (dynamic-func "strverscmp" (dynamic-link))
572 (error "could not find `strverscmp' (from GNU libc)"))))
573 (pointer->procedure int sym (list '* '*)))))
575 "Return '> when A denotes a newer version than B,
576 '< when A denotes a older version than B,
577 or '= when they denote equal versions."
578 (let ((result (strverscmp (string->pointer a) (string->pointer b))))
579 (cond ((positive? result) '>)
580 ((negative? result) '<)
583 (define (version-prefix version-string num-parts)
584 "Truncate version-string to the first num-parts components of the version.
585 For example, (version-prefix \"2.1.47.4.23\" 3) returns \"2.1.47\""
586 (string-join (take (string-split version-string #\.) num-parts) "."))
588 (define (version-major+minor+point version-string)
589 "Return \"major>.<minor>.<point>\", where major, minor and point are the
590 major, minor and point version numbers from the version-string. For example,
591 (version-major+minor+point \"6.4.5.2\") returns \"6.4.5\" or
592 (version-major+minor+point \"1.19.2-2581-324ca14c3003\") returns \"1.19.2\"."
593 (let* ((3-dot (version-prefix version-string 3))
594 (index (string-index 3-dot #\-)))
595 (or (false-if-exception (substring 3-dot 0 index))
598 (define (version-major+minor version-string)
599 "Return \"<major>.<minor>\", where major and minor are the major and
600 minor version numbers from version-string."
601 (version-prefix version-string 2))
603 (define (version-major version-string)
604 "Return the major version number as string from the version-string."
605 (version-prefix version-string 1))
607 (define (version-unique-prefix version versions)
608 "Return the shortest version prefix to unambiguously identify VERSION among
609 VERSIONS. For example:
611 (version-unique-prefix \"2.0\" '(\"3.0\" \"2.0\"))
614 (version-unique-prefix \"2.2\" '(\"3.0.5\" \"2.0.9\" \"2.2.7\"))
617 (version-unique-prefix \"27.1\" '(\"27.1\"))
621 (char-set-complement (char-set #\.)))
623 (define other-versions
624 (delete version versions))
626 (let loop ((prefix '())
627 (components (string-tokenize version not-dot)))
629 (string-join prefix "."))
631 (if (any (cut string-prefix? prefix-str <>) other-versions)
634 (loop `(,@prefix ,head) tail))
639 (define (version>? a b)
640 "Return #t when A denotes a version strictly newer than B."
641 (eq? '> (version-compare a b)))
643 (define (version>=? a b)
644 "Return #t when A denotes a version newer or equal to B."
645 (case (version-compare a b)
649 (define (guile-version>? str)
650 "Return #t if the running Guile version is greater than STR."
651 ;; Note: Using (version>? (version) "2.0.5") or similar doesn't work,
652 ;; because the result of (version) can have a prefix, like "2.0.5-deb1".
653 (version>? (string-append (major-version) "."
658 (define version-prefix?
659 (let ((not-dot (char-set-complement (char-set #\.))))
661 "Return true if V1 is a version prefix of V2:
663 (version-prefix? \"4.1\" \"4.16.2\") => #f
664 (version-prefix? \"4.1\" \"4.1.2\") => #t
666 (define (list-prefix? lst1 lst2)
673 (and (equal? head1 head2)
674 (list-prefix? tail1 tail2)))))))
676 (list-prefix? (string-tokenize v1 not-dot)
677 (string-tokenize v2 not-dot)))))
684 (define (file-extension file)
685 "Return the extension of FILE or #f if there is none."
686 (let ((dot (string-rindex file #\.)))
687 (and dot (substring file (+ 1 dot) (string-length file)))))
689 (define (file-sans-extension file)
690 "Return the substring of FILE without its extension, if any."
691 (let ((dot (string-rindex file #\.)))
693 (substring file 0 dot)
696 (define (tarball-sans-extension tarball)
697 "Return TARBALL without its .tar.* or .zip extension."
698 (let ((end (or (string-contains tarball ".tar")
699 (string-contains tarball ".tgz")
700 (string-contains tarball ".zip"))))
701 (substring tarball 0 end)))
703 (define (compressed-file? file)
704 "Return true if FILE denotes a compressed file."
705 (->bool (member (file-extension file)
706 '("gz" "bz2" "xz" "lz" "lzma" "tgz" "tbz2" "zip"))))
708 (define (switch-symlinks link target)
709 "Atomically switch LINK, a symbolic link, to point to TARGET. Works
710 both when LINK already exists and when it does not."
711 (let ((pivot (string-append link ".new")))
712 (symlink target pivot)
713 (rename-file pivot link)))
715 (define* (string-replace-substring str substr replacement
718 (end (string-length str)))
719 "Replace all occurrences of SUBSTR in the START--END range of STR by
721 (match (string-length substr)
723 (error "string-replace-substring: empty substring"))
725 (let loop ((start start)
726 (pieces (list (substring str 0 start))))
727 (match (string-contains str substr start end)
729 (string-concatenate-reverse
730 (cons (substring str start) pieces)))
732 (loop (+ index substr-length)
734 (substring str start index)
737 (define (call-with-temporary-output-file proc)
738 "Call PROC with a name of a temporary file and open output port to that
739 file; close the file and delete it when leaving the dynamic extent of this
741 (let* ((directory (or (getenv "TMPDIR") "/tmp"))
742 (template (string-append directory "/guix-file.XXXXXX"))
743 (out (mkstemp! template)))
750 (false-if-exception (close out))
751 (false-if-exception (delete-file template))))))
753 (define (call-with-temporary-directory proc)
754 "Call PROC with a name of a temporary directory; close the directory and
755 delete it when leaving the dynamic extent of this call."
756 (let* ((directory (or (getenv "TMPDIR") "/tmp"))
757 (template (string-append directory "/guix-directory.XXXXXX"))
758 (tmp-dir (mkdtemp! template)))
764 (false-if-exception (delete-file-recursively tmp-dir))))))
766 (define (with-atomic-file-output file proc)
767 "Call PROC with an output port for the file that is going to replace FILE.
768 Upon success, FILE is atomically replaced by what has been written to the
769 output port, and PROC's result is returned."
770 (let* ((template (string-append file ".XXXXXX"))
771 (out (mkstemp! template)))
772 (with-throw-handler #t
774 (let ((result (proc out)))
777 (rename-file template file)
780 (false-if-exception (delete-file template))
783 (define* (xdg-directory variable suffix #:key (ensure? #t))
784 "Return the name of the XDG directory that matches VARIABLE and SUFFIX,
785 after making sure that it exists if ENSURE? is true. VARIABLE is an
786 environment variable name like \"XDG_CONFIG_HOME\"; SUFFIX is a suffix like
787 \"/.config\". Honor the XDG specs,
788 <http://standards.freedesktop.org/basedir-spec/basedir-spec-latest.html>."
789 (let ((dir (and=> (or (getenv variable)
790 (and=> (or (getenv "HOME")
791 (passwd:dir (getpwuid (getuid))))
792 (cut string-append <> suffix)))
793 (cut string-append <> "/guix"))))
798 (define config-directory
799 (cut xdg-directory "XDG_CONFIG_HOME" "/.config" <...>))
801 (define cache-directory
802 (cut xdg-directory "XDG_CACHE_HOME" "/.cache" <...>))
804 (define (readlink* file)
805 "Call 'readlink' until the result is not a symlink."
806 (define %max-symlink-depth 50)
808 (let loop ((file file)
810 (define (absolute target)
811 (if (absolute-file-name? target)
813 (string-append (dirname file) "/" target)))
815 (if (>= depth %max-symlink-depth)
821 (values #t (readlink file)))
823 (let ((errno (system-error-errno args)))
824 (if (or (= errno EINVAL))
826 (apply throw args))))))
827 (lambda (success? target)
829 (loop (absolute target) (+ depth 1))
832 (define (canonical-newline-port port)
833 "Return an input port that wraps PORT such that all newlines consist
834 of a single linefeed."
835 (define (get-position)
836 (if (port-has-port-position? port) (port-position port) #f))
837 (define (set-position! position)
838 (if (port-has-set-port-position!? port)
839 (set-port-position! position port)
841 (define (close) (close-port port))
842 (define (read! bv start n)
844 (byte (get-u8 port)))
845 (cond ((eof-object? byte) count)
846 ;; XXX: consume all CRs even if not followed by LF.
847 ((eqv? byte (char->integer #\return)) (loop count (get-u8 port)))
849 (bytevector-u8-set! bv (+ start count) byte)
852 (bytevector-u8-set! bv (+ start count) byte)
853 (loop (+ count 1) (get-u8 port))))))
854 (make-custom-binary-input-port "canonical-newline-port"
864 (define absolute-dirname
865 ;; Memoize to avoid repeated 'stat' storms from 'search-path'.
867 "Return the absolute name of the directory containing FILE, or #f upon
869 (match (search-path %load-path file)
872 ;; If there are relative names in %LOAD-PATH, FILE can be relative and
873 ;; needs to be canonicalized.
874 (if (string-prefix? "/" file)
876 (canonicalize-path (dirname file)))))))
878 (define-syntax current-source-directory
880 "Return the absolute name of the current directory, or #f if it could not
884 (match (assq 'filename (or (syntax-source s) '()))
885 (('filename . (? string? file-name))
886 ;; If %FILE-PORT-NAME-CANONICALIZATION is 'relative, then FILE-NAME
887 ;; can be relative. In that case, we try to find out at run time
888 ;; the absolute file name by looking at %LOAD-PATH; doing this at
889 ;; run time rather than expansion time is necessary to allow files
890 ;; to be moved on the file system.
891 (if (string-prefix? "/" file-name)
893 #`(absolute-dirname #,file-name)))
894 ((or ('filename . #f) #f)
895 ;; raising an error would upset Geiser users
900 ;;; String comparison.
903 (define (string-distance s1 s2)
904 "Compute the Levenshtein distance between two strings."
905 ;; Naive implemenation
921 (let ((c1 (string->list s1))
922 (c2 (string->list s2)))
925 (define* (string-closest trial tests #:key (threshold 3))
926 "Return the string from TESTS that is the closest from the TRIAL,
927 according to 'string-distance'. If the TESTS are too far from TRIAL,
928 according to THRESHOLD, then #f is returned."
929 (identity ;discard second return value
930 (fold2 (lambda (test closest minimal)
931 (let ((dist (string-distance trial test)))
932 (if (and (< dist minimal) (< dist threshold))
934 (values closest minimal))))
939 ;;; eval: (put 'call-with-progress-reporter 'scheme-indent-function 1)