-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathmastertodo.hs
64 lines (49 loc) · 1.57 KB
/
mastertodo.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
import System.IO
import System.Directory
import System.Environment
import Data.List (lookup)
delete :: Int -> [a] -> [a]
delete 0 a = tail a
delete n (h:t) = [h] ++ delete (n-1) t
dispatch :: [(String, [String] -> IO ())]
dispatch = [("add", add) , ("view", view), ("remove", remove), ("bump", bump)]
main = do
(command:args) <- getArgs
let (Just action) = lookup command dispatch
action args
add :: [String] -> IO ()
add [path, toAppend] = do
appendFile path (toAppend ++ "\n")
view :: [String] -> IO ()
view [path] = do
contents <- readFile path
let tasks = lines contents
numTasks = zipWith (\n task -> show n ++ " - " ++ task) [1..] tasks
putStr $ unlines numTasks
remove :: [String] -> IO ()
remove [path, strNum] = do
handle <- openFile path ReadMode
(tempName, tempHandle) <- openTempFile "." "temp"
contents <- hGetContents handle
let num = read strNum
tasks = lines contents
modified = delete (num - 1) tasks
hPutStr tempHandle $ unlines modified
hClose tempHandle
hClose handle
removeFile path
renameFile tempName path
bump :: [String] -> IO ()
bump [path, strNum] = do
handle <- openFile path ReadMode
(tempName, tempHandle) <- openTempFile "." "temp"
contents <- hGetContents handle
let tasks = lines contents
num = read strNum - 1
bumping = tasks !! num
modified = delete num tasks
hPutStr tempHandle $ unlines $ [bumping] ++ modified
hClose tempHandle
hClose handle
removeFile path
renameFile tempName path