1
0
mirror of https://github.com/h7x4/nix-attr-search.git synced 2025-01-28 20:00:49 +01:00
nix-attr-search/internals/json2nix/json2nix.hs
h7x4 f6217e4c54
Restructure project:
The project has grown quite a bit without me remembering
to make any commits...

Here's a summary of what has happened:

- Make the project friendly towards non-flake users
- Add searchers to be created: `nur-package-search`, `nix-lib-search`
- Add misc util scripts for formatting and testing code.
- Split templates into their own directory,
    as they get quite large after a while.

- Add colorized templates.
- Replace some of the xml tags with optionally colorized output.
- Add `--no-color` option
- Add json2nix script, which will convert the json-converted
    nix code back into nix.
2022-11-26 05:14:14 +01:00

36 lines
1.2 KiB
Haskell

{-# LANGUAGE OverloadedStrings #-}
import Data.Aeson (Value(..), decode)
import Data.Aeson.Key (Key, toString)
import Data.Aeson.KeyMap (foldMapWithKey)
import Data.Aeson.Parser (json')
import Data.Aeson.Types (parse)
import Data.String (fromString)
import Data.Text (Text(..), unpack, replace, isInfixOf)
import Data.Vector (Vector)
import Data.Maybe (fromMaybe)
main :: IO ()
main = interact f
where
f input = case decode $ fromString input of
Nothing -> "json2nix error - could not parse input\n" ++ show input
Just jsonValue -> json2Nix jsonValue
keyValToString :: Key -> Value -> String
keyValToString key value = toString key ++ " = " ++ json2Nix value ++ ";"
-- escapeDollar :: Text -> Text
-- escapeDollar = replace "''${" "\\''${"
json2Nix :: Value -> String
json2Nix (Object object) = "{" ++ foldMapWithKey keyValToString object ++ "}"
json2Nix (Array array) = "[" ++ foldr (\x y -> x ++ " " ++ y) "" (fmap json2Nix array) ++ "]"
json2Nix (Number n) = show n
json2Nix (Bool False) = "false"
json2Nix (Bool True) = "true"
json2Nix Null = "null"
json2Nix (String text) = sep ++ unpack text ++ sep
where
sep = if "\"" `isInfixOf` text then "\'\'" else "\""