-
Notifications
You must be signed in to change notification settings - Fork 0
/
todoApp.hs
80 lines (65 loc) · 2.33 KB
/
todoApp.hs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
import Control.Exception
import Data.List
import System.Directory
import System.Environment
import System.IO
dispatch :: String -> [String] -> IO ()
dispatch "add" = add
dispatch "view" = view
dispatch "remove" = remove
dispatch "bump" = bump
dispatch wrongInput = failMessage wrongInput
disptach _ = fullBlownError
bump :: [String] -> IO ()
bump [fileName, numberString] = do
contents <- readFile fileName
let todoTasks = lines contents
number = read numberString
newTodoItems = unlines $ (todoTasks !! number) : delete (todoTasks !! number) todoTasks
bracketOnError (openTempFile "." "temp")
(\(tempName, tempHandle) -> do
hClose tempHandle
removeFile tempName)
(\(tempName, tempHandle) -> do
hPutStr tempHandle newTodoItems
hClose tempHandle
removeFile fileName
renameFile tempName fileName)
fullBlownError :: IO ()
fullBlownError =
putStrLn "Invalid input, please try again."
failMessage :: String -> [String] -> IO ()
failMessage msg _ =
putStrLn $ "I'm sorry I don't recognize command " ++ msg
add :: [String] -> IO ()
add [fileName, todoItem] = appendFile fileName (todoItem ++ "\n")
view :: [String] -> IO ()
view [fileName] = do
contents <- readFile fileName
let todoTasks = lines contents
numberedTasks = zipWith (\n line -> show n ++ " - " ++ line )
[0..] todoTasks
putStr $ unlines numberedTasks
remove :: [String] -> IO ()
remove [fileName, numberString] = do
contents <- readFile fileName
let todoTasks = lines contents
numberedTasks = zipWith (\n line -> show n ++ " - " ++ line )
[0..] todoTasks
number = read numberString
newTodoItems = unlines $ delete (todoTasks !! number) todoTasks
bracketOnError (openTempFile "." "temp")
(\(tempName, tempHandle) -> do
hClose tempHandle
removeFile tempName)
(\(tempName, tempHandle) -> do
hPutStr tempHandle newTodoItems
hClose tempHandle
removeFile fileName
renameFile tempName fileName)
putStrLn "These are your remaining Todo items: "
mapM_ putStrLn $ zipWith (\n line -> show n ++ " - " ++ line)
[0..] $ lines newTodoItems
main = do
(command:argList) <- getArgs
dispatch command argList