1
0
Fork 0
nixos-config/Main.hs

50 lines
1.7 KiB
Haskell
Raw Normal View History

2021-10-12 22:47:01 +00:00
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE ViewPatterns #-}
{-# LANGUAGE NoImplicitPrelude #-}
{-# OPTIONS_GHC -Wno-orphans #-}
import Relude
import Witch
2021-10-13 16:20:14 +00:00
import Data.Aeson (FromJSON (..), Value (Array, String), withObject)
import qualified Data.Aeson.Key as Key
import qualified Data.Aeson.KeyMap as Aeson
import qualified Data.Foldable as Foldable
2021-10-12 23:48:22 +00:00
import qualified Data.Text as Text
import Data.Yaml (decodeFileEither)
2021-10-12 22:47:01 +00:00
2021-10-13 16:20:14 +00:00
import System.Posix.Daemon (Redirection (DevNull), runDetached)
import System.Process (callCommand)
import Dialog (Menu (..), MenuEntry (Option, SubMenu), menu, runClearingHaskeline)
2021-10-12 23:48:22 +00:00
data Command = Run Text | Fork Text deriving (Show)
2021-10-12 22:47:01 +00:00
instance FromJSON (Menu Command) where
parseJSON = parseMenu "Hotkeys"
where
2021-10-13 16:20:14 +00:00
parseList name = (fmap (Menu name) .) $
mapM $ \(Key.toText -> key, val) ->
case val of
String cmd -> pure $ Dialog.Option key (text2cmd cmd)
innerObj -> Dialog.SubMenu <$> parseMenu key innerObj
unpackMenu (Array arr) = join <$> mapM unpackMenu (reverse $ Foldable.toList arr)
unpackMenu value = withObject "mapping to menu entries" (pure . reverse . Aeson.toList) value
parseMenu name = parseList name <=< unpackMenu
2021-10-12 23:48:22 +00:00
text2cmd t = if Text.isPrefixOf "fork " t then Fork (Text.drop 5 t) else Run t
2021-10-12 22:47:01 +00:00
main :: IO ()
main = do
2021-10-12 23:48:22 +00:00
[menuFileName] <- getArgs
menuCommand <- decodeFileEither menuFileName
2021-10-12 22:47:01 +00:00
case menuCommand of
2021-10-12 23:48:22 +00:00
Left err -> print err
2021-10-12 22:47:01 +00:00
Right a -> do
cmd <- runClearingHaskeline $ menu Nothing a
maybe pass runCommand cmd
runCommand :: Command -> IO ()
2021-10-12 23:48:22 +00:00
runCommand (Run cmd) = callCommand $ into cmd
runCommand (Fork cmd) = runDetached Nothing DevNull (callCommand $ into cmd)