add flagsToString
[hdata.git] / Add.hs
blobca34137d65d728194fcd381ed32e6b729ba0e9fa
1 module Add (
2 add,
3 usageAdd
4 ) where
6 import Data.List
7 import Util
9 data Flag = Path String
10 | Title String
11 | Authors String
12 | Keywords String
13 | Journal String
14 | Issue String
15 | Date String
16 | Pages String
17 deriving (Show)
19 isFlag :: String -> Bool
20 isFlag f = f `elem` ["-f","-p","-t","-j","-i","-d","-a","-k"]
22 add :: [String] -> IO ()
23 add [] = error $ "add: no arguments specified ('" ++ progName ++ " add help' for help)"
24 add argv = if isHelp $ head argv
25 then do putStrLn usageAdd
26 else do
27 case parseFlags argv of
28 Left msg -> error $ "add: " ++ msg
29 Right flags -> putStr $ flagsToString flags
31 flagsToString :: [Flag] -> String
32 flagsToString xs = foldl' step [] xs
33 where step ys x = show x ++ "\n" ++ ys
35 parseFlags :: [String] -> Either String [Flag]
36 parseFlags argv = parseFlags' [] argv
37 where parseFlags' _ (x:[]) = Left "too few arguments"
38 parseFlags' fs [] = Right fs
39 parseFlags' fs xs =
40 let flag = getFlag xs
41 in case flag of
42 Left msg -> Left msg
43 Right f -> parseFlags' (f:fs) (dropWhile (not . isFlag) (tail xs))
45 getFlag :: [String] -> Either String Flag
46 getFlag x@(x0:x1:_) =
47 let flag = case x0 of
48 "-f" -> Path x1
49 "-t" -> Title x1
50 "-j" -> Journal x1
51 "-i" -> Issue x1
52 "-d" -> Date x1
53 "-p" -> Pages x1
54 "-k" -> Keywords $ getValues $ tail x
55 "-a" -> Authors $ getValues $ tail x
56 in if isFlag x1
57 then Left "too few argument"
58 else Right flag
60 getValues :: [String] -> String
61 getValues argv = intercalate "|" $ takeWhile (not . isFlag) argv
63 usageAdd :: String
64 usageAdd = "usage: " ++ progName ++ " add <filters>\n\
65 \filters:\n\
66 \ -f <file>\n\
67 \ -t <title>\n\
68 \ -a <author1 [author2] ...>\n\
69 \ -k <keyword1 [keyword2] ...>\n\
70 \ -j <journal>\n\
71 \ -i <issue>\n\
72 \ -d <date>\n\
73 \ -p <page-from>-<page-to>"