Skip to content

Instantly share code, notes, and snippets.

@znxkznxk1030
Created February 4, 2021 05:22
Show Gist options
  • Save znxkznxk1030/1d73126ba7c5499fc65ba4443899866e to your computer and use it in GitHub Desktop.
Save znxkznxk1030/1d73126ba7c5499fc65ba4443899866e to your computer and use it in GitHub Desktop.
import System.Environment
import System.Directory ( removeFile, renameFile )
import System.IO
( hClose,
openFile,
hGetContents,
hPutStr,
openTempFile,
IOMode(ReadMode) )
import Data.List ( delete )
import Control.Exception ( bracketOnError )
main = do
(cmd: args) <- getArgs
dispatch cmd args
dispatch :: String -> [String] -> IO()
dispatch "add" = add
dispatch "view" = view
dispatch "remove" = remove
dispatch command = doesNotExist command
add :: [String] -> IO()
add [fileName, todoItem] = appendFile fileName todoItem
view :: [String] -> IO()
view [fileName]= do
handle <- openFile fileName ReadMode
contents <- hGetContents handle
let todoTasks = lines contents
nTodoTasks = zipWith (\n line -> show n ++ line ++ "\n") [0..] todoTasks
putStr $ unlines nTodoTasks
remove :: [String] -> IO()
remove [fileName, numberString] = do
handle <- openFile fileName ReadMode
contents <- hGetContents handle
let todoTasks = lines contents
number = read numberString
newTodoTasks = unlines $ delete (todoTasks !! number) todoTasks
bracketOnError (openTempFile "." "temp")
(\ (tempName, tempHandle) -> do
hClose tempHandle
removeFile tempName)
(\ (tempName, tempHandle) -> do
hPutStr tempHandle newTodoTasks
hClose tempHandle
removeFile fileName
renameFile tempName fileName)
doesNotExist :: String -> [String] -> IO()
doesNotExist command _ = do
putStrLn $ command ++ " does not exist"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment