Skip to content

Instantly share code, notes, and snippets.

@jmn
Created March 7, 2018 15:49
Show Gist options
  • Save jmn/fccd440852a124c38530799aac68581c to your computer and use it in GitHub Desktop.
Save jmn/fccd440852a124c38530799aac68581c to your computer and use it in GitHub Desktop.
Haskell CmdArgs optional positional arguments
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE DeriveDataTypeable #-}
module Main where
import Lib
import System.Environment (getArgs)
import Database.SQLite.Simple
import System.Console.CmdArgs
import Data.List
data Options = Options {
inputMode :: Bool,
message :: String
} deriving (Data, Typeable)
options :: Options
options = Options { inputMode = False
&= typ "Input mode"
&= help "Toggle input mode",
message = def
&= typ "message"
&= opt ("" :: String)
&= args
}
&= summary "n notes"
&= program "n"
data TestField = TestField Int String deriving (Show)
instance FromRow TestField where
fromRow = TestField <$> field <*> field
instance ToRow TestField where
toRow (TestField id_ str) = toRow (id_, str)
dbPut conn val =
execute conn "INSERT INTO test (str) VALUES (?)" (Only (val :: String))
main :: IO ()
main = do
opts <- cmdArgs options
conn <- open "test.db"
execute_ conn "CREATE TABLE IF NOT EXISTS test (id INTEGER PRIMARY KEY, str TEXT)"
case (message opts) of
"" -> return ()
x -> dbPut conn x
case (inputMode opts) of
True -> do
content <- getContents
dbPut conn content
False ->
return ()
r <- query_ conn "SELECT * from test" :: IO [TestField]
mapM_ print r
close conn
@jmn
Copy link
Author

jmn commented Mar 7, 2018

Note: This program behaves weird when running in GHCi but seems to work fine when compiled.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment