hierarchical config, fetch env data from root config when updating slots of child

This commit is contained in:
Helmut Merz 2024-06-07 19:35:46 +02:00
parent 81043d0e35
commit 27542c5c40
3 changed files with 20 additions and 9 deletions

View file

@ -49,13 +49,19 @@
((parent :reader parent ((parent :reader parent
:initarg :parent))) :initarg :parent)))
(defmethod initialize-instance :after ((cfg base) &key parent &allow-other-keys)
(push cfg (children parent)))
(defmethod (setf parent) ((cfg base) (parent common))
(push cfg (children parent)))
(defgeneric add (cfg child) (defgeneric add (cfg child)
(:method ((cfg common) (child base)) (:method ((cfg common) (child base))
(push (children cfg) child) (push child (children cfg))
(setf (parent child) cfg))) (setf (parent child) cfg)))
(defmethod env-data ((cfg base)) (defmethod env-data ((cfg base))
(env-data (parent (cfg)))) (env-data (parent cfg)))
;;;; utility functions ;;;; utility functions

View file

@ -6,3 +6,5 @@
(setf *config* (setf *config*
(make-instance 'test-config)) (make-instance 'test-config))
(make-instance 'child-config :parent *config*)

View file

@ -16,11 +16,13 @@
(defclass test-config (config:root) (defclass test-config (config:root)
((config:env-keys :initform '(:user :password)) ((config:env-keys :initform '(:user :password))
(config:env-path :initform (t:test-path ".test.env")) (config:env-path :initform (t:test-path ".test.env"))))
(user :accessor user :initarg :user)
(defclass child-config (config:base)
((user :accessor user :initarg :user)
(password :accessor password :initarg :password))) (password :accessor password :initarg :password)))
(defmethod initialize-instance :after ((cfg test-config) &key &allow-other-keys) (defmethod initialize-instance :after ((cfg child-config) &key &allow-other-keys)
(config:hash-to-slots (config:env-data cfg) cfg '(user password))) (config:hash-to-slots (config:env-data cfg) cfg '(user password)))
(defun run () (defun run ()
@ -38,8 +40,9 @@
(== (pathname-name (util:home-path ".env.txt" "lisp" "cl-scopes")) ".env")) (== (pathname-name (util:home-path ".env.txt" "lisp" "cl-scopes")) ".env"))
(t:deftest test-env-override () (t:deftest test-env-override ()
(let ((data (config:env-data *config*))) (let ((data (config:env-data *config*))
(child (car (config:children *config*))))
(== (gethash :user data) "user-from-env-file") (== (gethash :user data) "user-from-env-file")
(== (gethash :password data) "very_secret") (== (gethash :password data) "very_secret")
(== (user *config*) "user-from-env-file") (== (user child) "user-from-env-file")
(== (password *config*) "very_secret"))) (== (password child) "very_secret")))