From aca3bce2cd8106e54c8ba24623ae7f17340dae9e Mon Sep 17 00:00:00 2001 From: drlkf Date: Tue, 24 Nov 2026 17:54:15 +0100 Subject: [PATCH] fix(set): allow writing keys in unset sections with default values --- src/Effectful/CLI/Config.hs | 18 ++++++++++++------ test/Spec.hs | 8 ++++++++ 2 files changed, 20 insertions(+), 6 deletions(-) diff --git a/src/Effectful/CLI/Config.hs b/src/Effectful/CLI/Config.hs index 3e7ac3a..8fdfb35 100644 --- a/src/Effectful/CLI/Config.hs +++ b/src/Effectful/CLI/Config.hs @@ -14,6 +14,7 @@ module Effectful.CLI.Config ( import Control.Monad ((<=<)) import Data.Error.CLI (CLIError (..)) +import Data.List (isInfixOf) import Data.Map.Strict qualified as Map import Data.Maybe (fromMaybe) import Data.Text (Text) @@ -82,7 +83,8 @@ getConfigKey path key = render v = T.show (prettyValue v) -- | Set a dotted key to 'parseValue' of the raw input, creating intermediate --- tables; the file is only written if the result still decodes as @a@. +-- tables; the file is only written if the result still decodes as @a@, +-- ignoring missing required keys. -- Re-renders the whole file, dropping comments and formatting. -- -- When decoding fails and @key@ is a section of one of the known keys, the @@ -106,14 +108,18 @@ setConfigKey known path key raw = do either (throwError . InputError) pure . setKey (T.splitOn "." key) (parseValue raw) =<< readTable path let rendered = T.show (prettyToml table) - case Toml.decode @a rendered of - Failure es -> - throwError - (InputError ("invalid config: " <> T.stripEnd (T.pack (unlines es)) <> sectionHint)) - Success _ _ -> liftIO $ do + case decodeErrors rendered of + [] -> liftIO $ do createDirectoryIfMissing True (takeDirectory path) T.writeFile path rendered + es -> + throwError + (InputError ("invalid config: " <> T.stripEnd (T.pack (unlines es)) <> sectionHint)) where + -- missing required keys are tolerated so sections can be filled one key at a time + decodeErrors r = case Toml.decode @a r of + Failure es -> filter (not . isInfixOf "missing key: ") es + Success _ _ -> [] sectionHint = case filter (T.isPrefixOf (key <> ".")) known of [] -> "" ks -> "; " <> key <> " is a section, set one of: " <> T.intercalate ", " ks diff --git a/test/Spec.hs b/test/Spec.hs index 9d194cc..3b17a27 100644 --- a/test/Spec.hs +++ b/test/Spec.hs @@ -171,6 +171,14 @@ main = hspec $ do Left (InputError m) -> "sec is a section, set one of: sec.x, sec.y" `isInfixOf` show m _ -> False + it "sets a key in a section missing required keys" $ do + path <- ( "effectful-cli-config-partial-test.toml") <$> getTemporaryDirectory + r <- runEff . runErrorNoCallStack @CLIError $ do + setConfigKey @Section [] path "sec.y" "1" + getConfigKey path "sec.y" + removeFile path + r `shouldBe` Right "1" + it "shows defaults for a missing file and file values over them" $ do dir <- getTemporaryDirectory let missing = dir "effectful-cli-config-missing.toml"