on 552fe26 help sign in
elk/server/Server.hs
89 lines 2.9 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.Directory
11import System.Environment
12import System.FilePath
13import System.Process
14import qualified Language.Elm as Elm
15import Paths_elm_server
17runtime = "/elm-runtime.js"
19serve :: Int -> String -> IO ()
20serve portNumber libLoc = do
21 putStrLn $ "Elm Server " ++ showVersion version ++
22 ": running at <http://localhost:" ++ show portNumber ++ ">"
23 putStrLn "Just refresh a page to recompile it!"
24 simpleHTTP httpConf $ do
25 _ <- compressedResponseFilter
26 msum [ uriRest serveElm
27 , uriRest (serveLib libLoc)
28 , serveDirectory EnableBrowsing [] "."
29 ]
30 where httpConf = nullConf { port = portNumber }
32pageTitle :: String -> String
33pageTitle = dropExtension . takeBaseName
35serveElm :: FilePath -> ServerPartT IO Response
36serveElm fp = do
37 guard (takeExtension fp == ".elm")
38 let file = tail fp
39 liftIO $ rawSystem "elm" [ "--make" ,"--runtime=" ++ runtime
40 , "--cache-dir=elm-server-cache", file ]
41 liftIO $ removeDirectoryRecursive "elm-server-cache"
42 serveFile (asContentType "text/html") ("build" </> replaceExtension file "html")
44serveLib :: FilePath -> [Char] -> ServerPartT IO Response
45serveLib libLoc fp = do
46 guard (fp == runtime)
47 serveFile (asContentType "application/javascript") libLoc
49main :: IO ()
50main = getArgs >>= parse
52parse :: [String] -> IO ()
53parse ("--help":_) = putStrLn usage
54parse ("--version":_) = putStrLn ("The Elm Server " ++ showVersion version)
55parse args =
56 case null remainingArgs of
57 True -> serve portNumber =<< elmRuntime
58 False -> putStrLn usageMini
59 where
60 runtimeArg = filter (isPrefixOf "--runtime-location=") args
61 portArg = filter (isPrefixOf "--port=") args
62 remainingArgs = (args \\ runtimeArg) \\ portArg
64 argValue arg = tail $ dropWhile (/= '=') (head arg)
65 portNumber = if null portArg then 8000 else read (argValue portArg) :: Int
66 elmRuntime = if null runtimeArg then Elm.runtime else return $ argValue runtimeArg
68usageMini :: String
69usageMini =
70 "Usage: elm-server [OPTIONS]\n\
71 \Try `elm-server --help' for more information."
73usage :: String
74usage =
75 "Usage: elm-server [OPTIONS]\n\
76 \Compiles and serves .elm files from the current directory.\n\
77 \Example: elm-server\n\
78 \\n\
79 \Server configuration:\n\
80 \ --port set the port to listen on (default: 8000)\n\
81 \\n\
82 \Resource Locations:\n\
83 \ --runtime-location set the location of the Elm runtime\n\
84 \\n\
85 \Compiler Information:\n\
86 \ --version print the version information and exit\n\
87 \ --help display this help and exit\n\
88 \\n\
89 \Elm home page: <http://elm-lang.org>"