From 8af749224fd69daee5b67295186c77becb1a4479 Mon Sep 17 00:00:00 2001
From: Ludovic Courtès <ludo@gnu.org>
Date: Wed, 13 Jul 2022 17:14:20 +0200
Subject: home: services: shells: Double-quote environment variable values.

Fixes <https://issues.guix.gnu.org/56540>.

Until now, environment variable values were emitted unquoted, producing
invalid shell code if the value contains spaces for example.

* gnu/home/services/shells.scm (serialize-posix-env-vars): Define
'shell-quote' procedure in staged code and use it for #$value.
* tests/guix-home.sh: Add test for PS1 variable with a value containing
spaces.
---
 gnu/home/services/shells.scm | 34 ++++++++++++++++++++++++----------
 1 file changed, 24 insertions(+), 10 deletions(-)

(limited to 'gnu/home/services')

diff --git a/gnu/home/services/shells.scm b/gnu/home/services/shells.scm
index 27190934f0..28d717f03d 100644
--- a/gnu/home/services/shells.scm
+++ b/gnu/home/services/shells.scm
@@ -111,16 +111,30 @@ service type can be extended with a list of file-like objects.")))
 
 (define (serialize-boolean field-name val) "")
 (define (serialize-posix-env-vars field-name val)
-  #~(string-append
-     #$@(map
-         (match-lambda
-           ((key . #f)
-            "")
-           ((key . #t)
-            #~(string-append "export " #$key "\n"))
-           ((key . value)
-            #~(string-append "export " #$key "=" #$value "\n")))
-         val)))
+  #~(let ((shell-quote
+           (lambda (value)
+             ;; Double-quote VALUE, leaving dollar sign as is.
+             (let ((quoted (list->string
+                            (string-fold-right
+                             (lambda (chr lst)
+                               (case chr
+                                 ((#\" #\\)
+                                  (append (list chr #\\) lst))
+                                 (else (cons chr lst))))
+                             '()
+                             value))))
+               (string-append "\"" quoted "\"")))))
+      (string-append
+       #$@(map
+           (match-lambda
+             ((key . #f)
+              "")
+             ((key . #t)
+              #~(string-append "export " #$key "\n"))
+             ((key . value)
+              #~(string-append "export " #$key "="
+                               (shell-quote #$value) "\n")))
+           val))))
 
 
 ;;;
-- 
cgit v1.2.3