Created
February 4, 2021 05:22
-
-
Save znxkznxk1030/1d73126ba7c5499fc65ba4443899866e to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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