on e4e8d89 help sign in
elk/server/Server.hs
80 lines 2.7 kB history raw
2module Main where
4import Control.Monad (msum,guard)
5import Control.Monad.Trans (MonadIO(liftIO))
6import Data.List (isPrefixOf, isSuffixOf, (\\))
7import Data.Version (showVersion)
8import Happstack.Server
9import Happstack.Server.Compression
10import System.Environment
11import System.FilePath
12import qualified Language.Elm as Elm
13import Paths_elm_server
15runtime = "/elm-" ++ showVersion version ++ ".js"
17serve :: Int -> String -> IO ()
18serve portNumber libLoc = do
19 putStrLn ("Elm Server " ++ showVersion version ++
20 ": running at <http://localhost:" ++ (show portNumber) ++ ">")
21 putStrLn "Just refresh a page to recompile it!"
22 simpleHTTP httpConf $ do
23 _ <- compressedResponseFilter
24 msum [ uriRest serveElm
25 , uriRest (serveLib libLoc)
26 , serveDirectory EnableBrowsing [] "."
27 ]
28 where httpConf = nullConf { port = portNumber }
30pageTitle :: String -> String
31pageTitle = dropExtension . takeBaseName
33serveElm fp = do
34 guard (takeExtension fp == ".elm")
35 content <- liftIO (readFile (tail fp))
36 length content `seq` (ok . toResponse $ Elm.toHtml runtime (pageTitle fp) content)
38serveLib libLoc fp = do
39 guard (fp == runtime)
40 serveFile (asContentType "application/javascript") libLoc
42main :: IO ()
43main = getArgs >>= parse
45parse :: [String] -> IO ()
46parse ("--help":_) = putStrLn usage
47parse ("--version":_) = putStrLn ("The Elm Server " ++ showVersion version)
48parse args = if null remainingArgs
49 then serve portNumber =<< elmRuntime
50 else putStrLn usageMini
51 where runtimeArg = filter (isPrefixOf "--runtime-location=") args
52 portArg = filter (isPrefixOf "--port=") args
53 remainingArgs = (args \\ runtimeArg) \\ portArg
55 argValue arg = tail $ dropWhile (/= '=') (head arg)
56 portNumber = if null portArg then 8000 else read (argValue portArg) :: Int
57 elmRuntime = if null runtimeArg then Elm.runtime else return $ argValue runtimeArg
59usageMini :: String
60usageMini =
61 "Usage: elm-server [OPTIONS]\n\
62 \Try `elm-server --help' for more information."
64usage :: String
65usage =
66 "Usage: elm-server [OPTIONS]\n\
67 \Compiles and serves .elm files from the current directory.\n\
68 \Example: elm-server\n\
69 \\n\
70 \Server configuration:\n\
71 \ --port set the port to listen on (default: 8000)\n\
72 \\n\
73 \Resource Locations:\n\
74 \ --runtime-location set the location of the Elm runtime\n\
75 \\n\
76 \Compiler Information:\n\
77 \ --version print the version information and exit\n\
78 \ --help display this help and exit\n\
79 \\n\
80 \Elm home page: <http://elm-lang.org>"