on master help sign in
Merge branch 'master' into ts-fix-tests
commit32b9aae7483b7434df2dd43d45a2215ee62d6baf authorTom Smalley <tomsmalley@users.noreply.github.com> dateTue 30 Oct 2018, 14:18 (8 years ago) parent067024ab76ec1d
14 files changed+205−225
README.md+7−23 default.nix+1−2 lib/backend/obelisk-backend.cabal−1 lib/backend/src/Obelisk/Backend.hs+30−16 lib/command/src/Obelisk/Command/Deploy.hs+1 lib/command/src/Obelisk/Command/Nix.hs+1−7 lib/command/src/Obelisk/Command/Thunk.hs+11−3 lib/frontend/src/Obelisk/Frontend.hs+11−8 lib/route/src/Obelisk/Route/Frontend.hs+108−2 lib/run/src/Obelisk/Run.hs+7−6 lib/selftest/src/Obelisk/SelfTest.hs+28−17 lib/snap/obelisk-snap.cabal−40 lib/snap/src/Obelisk/Snap.hs−99 release.nix−1
README.md+7−23
@@ -57,29 +57,13 @@ nix-shell -A obelisk.obelisk-command.env --run "cd lib/command && ghcid -c 'caba
5757```
5858
5959### Accessing private repositories
60−To allow the Nix builder to access private git repositories, follow these steps:
61−
62−1. [Get set up to connect to GitHub with SSH](https://help.github.com/articles/connecting-to-github-with-ssh/)
63−1. [Create a GitHub personal access token](https://help.github.com/articles/creating-a-personal-access-token-for-the-command-line/)
64−1. Set environment variables:
65− * NixOS: Add this to `/etc/nixos/configuration.nix`:
66− ```
67− nix.envVars = {
68− NIX_GITHUB_PRIVATE_USERNAME = "your-github-username";
69− NIX_GITHUB_PRIVATE_PASSWORD = "your-github-personal-access-token";
70− };
71− ```
72− * MacOS:
73− ```
74− sudo launchctl setenv NIX_GITHUB_PRIVATE_USERNAME "your-github-username"
75− sudo launchctl setenv NIX_GITHUB_PRIVATE_PASSWORD "your-github-personal-access"
76− sudo launchctl stop org.nixos.nix-daemon
77− sudo launchctl start org.nixos.nix-daemon
78− ```
79−1. `nix-env -i hub` OR `nix-env -iA nixos.gitAndTools.hub`
80−1. `hub clone yourusername/yourproject`
81− * NOTE: you must authenticate with hub at least once, because the `ob` command uses `hub` for authentication
82− #TODO: Make ob do this itself (either invoke hub automatically or not depend on hub)
60+
61+To allow the Nix builder to access private git repositories, you must be set up
62+to access them via SSH. Follow these steps depending on the platform you need
63+access to:
64+
65+- [GitHub](https://help.github.com/articles/connecting-to-github-with-ssh/)
66+- [GitLab](https://docs.gitlab.com/ee/gitlab-basics/create-your-ssh-keys.html)
8367
8468## Developing an Obelisk project
8569
default.nix+1−2
@@ -61,7 +61,6 @@ let
6161 obelisk-run = self.callCabal2nix "obelisk-run" (cleanSource ./lib/run) {};
6262 obelisk-route = self.callCabal2nix "obelisk-route" (cleanSource ./lib/route) {};
6363 obelisk-selftest = self.callCabal2nix "obelisk-selftest" (cleanSource ./lib/selftest) {};
64− obelisk-snap = self.callCabal2nix "obelisk-snap" (cleanSource ./lib/snap) {};
6564 obelisk-snap-extras = self.callCabal2nix "obelisk-snap-extras" (cleanSource ./lib/snap-extras) {};
6665 })
6766
@@ -135,7 +134,7 @@ in rec {
135134
136135 PATH="${command}/bin:$PATH"
137136 export OBELISK_IMPL="${hackGet ./.}"
138− "${ghcObelisk.obelisk-selftest}/bin/obelisk-selftest" "$@"
137+ "${ghcObelisk.obelisk-selftest}/bin/obelisk-selftest" +RTS -N -RTS "$@"
139138 '';
140139 #TODO: Why can't I build ./skeleton directly as a derivation? `nix-build -E ./.` doesn't work
141140 skeleton = pkgs.runCommand "skeleton" {
lib/backend/obelisk-backend.cabal−1
@@ -17,7 +17,6 @@ library
1717 obelisk-executable-config-inject,
1818 obelisk-frontend,
1919 obelisk-route,
20− obelisk-snap,
2120 reflex-dom,
2221 snap,
2322 snap-server,
lib/backend/src/Obelisk/Backend.hs+30−16
@@ -5,6 +5,7 @@
55{-# LANGUAGE LambdaCase #-}
66{-# LANGUAGE MultiParamTypeClasses #-}
77{-# LANGUAGE OverloadedStrings #-}
8+{-# LANGUAGE ScopedTypeVariables #-}
89{-# LANGUAGE TemplateHaskell #-}
910module Obelisk.Backend
1011 ( Backend (..)
@@ -16,6 +17,8 @@ module Obelisk.Backend
1617 , serveDefaultObeliskApp
1718 , prettifyOutput
1819 , runBackend
20+ , staticRenderContentType
21+ , mkRouteToUrl
1922 ) where
2023
2124import Prelude hiding (id, (.))
@@ -38,8 +41,8 @@ import Obelisk.ExecutableConfig.Inject (injectExecutableConfigs)
3841import Obelisk.Frontend
3942import Obelisk.Route
4043import Reflex.Dom
41−import Snap (MonadSnap, Snap, commandLineConfig, defaultConfig, getsRequest, httpServe, rqPathInfo,
42− rqQueryString, writeBS, writeText)
44+import Snap (MonadSnap, Snap, commandLineConfig, defaultConfig, getsRequest, httpServe, modifyResponse
45+ , rqPathInfo, rqQueryString, setContentType, writeBS, writeText)
4346import Snap.Internal.Http.Server.Config (Config (accessLog, errorLog), ConfigLog (ConfigIoLog))
4447import System.IO (BufferMode (..), hSetBuffering, stderr, stdout)
4548
@@ -56,8 +59,8 @@ data GhcjsApp route = GhcjsApp
5659
5760-- | Serve a frontend, which must be the same frontend that Obelisk has built and placed in the default location
5861--TODO: The frontend should be provided together with the asset paths so that this isn't so easily breakable; that will probably make this function obsolete
59−serveDefaultObeliskApp :: MonadSnap m => ([Text] -> m ()) -> Frontend (R appRoute) -> R (ObeliskRoute appRoute) -> m ()
60−serveDefaultObeliskApp serveStaticAsset frontend = serveObeliskApp serveStaticAsset frontendApp
62+serveDefaultObeliskApp :: MonadSnap m => (R appRoute -> Text) -> ([Text] -> m ()) -> Frontend (R appRoute) -> R (ObeliskRoute appRoute) -> m ()
63+serveDefaultObeliskApp urlEnc serveStaticAsset frontend = serveObeliskApp urlEnc serveStaticAsset frontendApp
6164 where frontendApp = GhcjsApp
6265 { _ghcjsApp_compiled = defaultFrontendGhcjsAssets
6366 , _ghcjsApp_value = frontend
@@ -108,12 +111,12 @@ getRouteWith e = do
108111 pageName <- getPageName
109112 return $ tryDecode e pageName
110113
111−serveObeliskApp :: MonadSnap m => ([Text] -> m ()) -> GhcjsApp (R appRoute) -> R (ObeliskRoute appRoute) -> m ()
112−serveObeliskApp serveStaticAsset frontendApp = \case
113− ObeliskRoute_App appRouteComponent :=> Identity appRouteRest -> serveGhcjsApp frontendApp $ GhcjsAppRoute_App appRouteComponent :/ appRouteRest
114+serveObeliskApp :: MonadSnap m => (R appRoute -> Text) -> ([Text] -> m ()) -> GhcjsApp (R appRoute) -> R (ObeliskRoute appRoute) -> m ()
115+serveObeliskApp urlEnc serveStaticAsset frontendApp = \case
116+ ObeliskRoute_App appRouteComponent :=> Identity appRouteRest -> serveGhcjsApp urlEnc frontendApp $ GhcjsAppRoute_App appRouteComponent :/ appRouteRest
114117 ObeliskRoute_Resource resComponent :=> Identity resRest -> case resComponent :=> Identity resRest of
115118 ResourceRoute_Static :=> Identity pathSegments -> serveStaticAsset pathSegments
116− ResourceRoute_Ghcjs :=> Identity pathSegments -> serveGhcjsApp frontendApp $ GhcjsAppRoute_Resource :/ pathSegments
119+ ResourceRoute_Ghcjs :=> Identity pathSegments -> serveGhcjsApp urlEnc frontendApp $ GhcjsAppRoute_Resource :/ pathSegments
117120 ResourceRoute_JSaddleWarp :=> Identity _ -> do
118121 let msg = "Error: Obelisk.Backend received jsaddle request"
119122 liftIO $ putStrLn $ T.unpack msg
@@ -132,11 +135,15 @@ data GhcjsAppRoute :: (* -> *) -> * -> * where
132135 GhcjsAppRoute_App :: appRouteComponent a -> GhcjsAppRoute appRouteComponent a
133136 GhcjsAppRoute_Resource :: GhcjsAppRoute appRouteComponent [Text]
134137
138+staticRenderContentType :: ByteString
139+staticRenderContentType = "text/html; charset=utf-8"
140+
135141--TODO: Don't assume we're being served at "/"
136−serveGhcjsApp :: MonadSnap m => GhcjsApp (R appRouteComponent) -> R (GhcjsAppRoute appRouteComponent) -> m ()
137−serveGhcjsApp app = \case
138− GhcjsAppRoute_App appRouteComponent :=> Identity appRouteRest ->
139− writeBS <=< liftIO $ renderGhcjsFrontend (appRouteComponent :/ appRouteRest) $ _ghcjsApp_value app
142+serveGhcjsApp :: MonadSnap m => (R appRouteComponent -> Text) -> GhcjsApp (R appRouteComponent) -> R (GhcjsAppRoute appRouteComponent) -> m ()
143+serveGhcjsApp urlEnc app = \case
144+ GhcjsAppRoute_App appRouteComponent :=> Identity appRouteRest -> do
145+ modifyResponse $ setContentType staticRenderContentType
146+ writeBS <=< liftIO $ renderGhcjsFrontend urlEnc (appRouteComponent :/ appRouteRest) $ _ghcjsApp_value app
140147 GhcjsAppRoute_Resource :=> Identity pathSegments -> serveStaticAssets (_ghcjsApp_compiled app) pathSegments
141148
142149runBackend :: Backend fullRoute frontendRoute -> Frontend (R frontendRoute) -> IO ()
@@ -147,10 +154,17 @@ runBackend backend frontend = case checkEncoder $ _backend_routeEncoder backend
147154 getRouteWith validFullEncoder >>= \case
148155 Identity r -> case r of
149156 InL backendRoute :=> Identity a -> serveRoute $ backendRoute :/ a
150− InR obeliskRoute :=> Identity a -> serveDefaultObeliskApp (serveStaticAssets defaultStaticAssets) frontend $ obeliskRoute :/ a
157+ InR obeliskRoute :=> Identity a ->
158+ serveDefaultObeliskApp (mkRouteToUrl validFullEncoder) (serveStaticAssets defaultStaticAssets) frontend $ obeliskRoute :/ a
159+
160+mkRouteToUrl :: Encoder Identity parse (R (Sum f (ObeliskRoute r))) PageName -> R r -> Text
161+mkRouteToUrl validFullEncoder =
162+ let pageNameEncoder' :: Encoder Identity (Either Text) PageName PathQuery = pageNameEncoder
163+ in \(k :/ v) -> T.pack . uncurry (<>) . encode pageNameEncoder' . encode validFullEncoder $ (InR $ ObeliskRoute_App k) :/ v
164+
151165
152−renderGhcjsFrontend :: route -> Frontend route -> IO ByteString
153−renderGhcjsFrontend route f = do
166+renderGhcjsFrontend :: MonadIO m => (route -> Text) -> route -> Frontend route -> m ByteString
167+renderGhcjsFrontend urlEnc route f = do
154168 let baseTag = elAttr "base" ("href" =: "/") blank --TODO: Figure out the base URL from the routes
155169 ghcjsScript = elAttr "script" ("language" =: "javascript" <> "src" =: "ghcjs/all.js" <> "defer" =: "defer") blank
156− renderFrontendHtml route (_frontend_head f >> injectExecutableConfigs >> baseTag) (_frontend_body f >> ghcjsScript)
170+ liftIO $ renderFrontendHtml urlEnc route (_frontend_head f >> injectExecutableConfigs >> baseTag) (_frontend_body f >> ghcjsScript)
lib/command/src/Obelisk/Command/Deploy.hs+1
@@ -177,6 +177,7 @@ verifyHostKey knownHostsPath keyPath hostName =
177177 callProcessAndLogOutput (Notice, Warning) $ proc "ssh" $
178178 sshArgs knownHostsPath keyPath True <>
179179 [ "root@" <> hostName
180+ , "-o", "NumberOfPasswordPrompts=0"
180181 , "exit"
181182 ]
182183
lib/command/src/Obelisk/Command/Nix.hs+1−7
@@ -18,20 +18,14 @@ module Obelisk.Command.Nix
1818 , strArg
1919 ) where
2020
21−--import Control.Monad.Catch (catch, throwM)
22−import Control.Lens
23−import Control.Monad.Except (ExceptT, runExceptT, throwError)
24−import Control.Monad.IO.Class (liftIO)
2521import Data.Bool (bool)
2622import Data.Default
2723import Data.List (intercalate)
2824import Data.Monoid ((<>))
2925import qualified Data.Text as T
30−import System.Directory
31−import System.Environment
3226import System.Process (proc)
3327
34−import Obelisk.App (MonadInfallibleObelisk, MonadObelisk, ObeliskError (..))
28+import Obelisk.App (MonadObelisk)
3529import Obelisk.CliApp
3630
3731-- | Where to put nix-build output
lib/command/src/Obelisk/Command/Thunk.hs+11−3
@@ -563,8 +563,16 @@ finalMsg noTrail s = if noTrail then Nothing else Just s
563563unpackThunk :: MonadObelisk m => FilePath -> m ()
564564unpackThunk = unpackThunk' False
565565
566+-- | Check that we are not somewhere inside the thunk directory
567+checkThunkDirectory :: MonadObelisk m => FilePath -> m ()
568+checkThunkDirectory thunkDir = do
569+ currentDir <- liftIO getCurrentDirectory
570+ thunkDir' <- liftIO $ canonicalizePath thunkDir
571+ when (thunkDir' `L.isInfixOf` currentDir) $
572+ failWith "Can't pack/unpack from within the thunk directory"
573+
566574unpackThunk' :: MonadObelisk m => Bool -> FilePath -> m ()
567−unpackThunk' noTrail thunkDir = readThunk thunkDir >>= \case
575+unpackThunk' noTrail thunkDir = checkThunkDirectory thunkDir >> readThunk thunkDir >>= \case
568576 Left err -> failWith $ "thunk unpack: " <> T.pack (show err)
569577 --TODO: Overwrite option that rechecks out thunk; force option to do so even if working directory is dirty
570578 Right (ThunkData_Checkout _) -> failWith "thunk unpack: thunk is already unpacked"
@@ -601,7 +609,7 @@ packThunk :: MonadObelisk m => FilePath -> m ()
601609packThunk = packThunk' False
602610
603611packThunk' :: MonadObelisk m => Bool -> FilePath -> m ()
604−packThunk' noTrail thunkDir = readThunk thunkDir >>= \case
612+packThunk' noTrail thunkDir = checkThunkDirectory thunkDir >> readThunk thunkDir >>= \case
605613 Left err -> failWith $ T.pack $ "thunk pack: " <> show err
606614 Right (ThunkData_Packed _) -> failWith "pack: thunk is already packed"
607615 Right (ThunkData_Checkout _) -> do
@@ -661,7 +669,7 @@ getThunkPtr' checkClean thunkDir = do
661669 let untrackedBranches = Map.keys errorMap
662670 when (not $ L.null untrackedBranches) $ failWith $ T.unlines $
663671 [ "thunk pack: Certain branches in the thunk have no upstream branch \
664− \set. This means don't know to check whether all your work is \
672+ \set. This means we don't know to check whether all your work is \
665673 \saved. The offending branches are:"
666674 , ""
667675 , T.unwords untrackedBranches
lib/frontend/src/Obelisk/Frontend.hs+11−8
@@ -32,6 +32,7 @@ import Data.Dependent.Sum (DSum (..))
3232import Data.Functor.Sum
3333import Data.IORef
3434import Data.Monoid ((<>))
35+import Data.Text (Text)
3536import GHCJS.DOM hiding (bracket, catch)
3637import GHCJS.DOM.Document
3738import GHCJS.DOM.Node
@@ -64,6 +65,7 @@ type ObeliskWidget t x route m =
6465 , PrimMonad m
6566 , Prerender x m
6667 , SetRoute t route m
68+ , RouteToUrl route m
6769 )
6870
6971data Frontend route = Frontend
@@ -143,22 +145,23 @@ runFrontend validFullEncoder frontend = do
143145 , MonadFix m
144146 , MonadFix (Performable m)
145147 )
146− => RoutedT t (R route) (SetRouteT t (R route) m) a
148+ => RoutedT t (R route) (SetRouteT t (R route) (RouteToUrlT (R route) m)) a
147149 -> m a
148150 runMyRouteViewT = runRouteViewT ve
149151 runWithHeadAndBody $ \appendHead appendBody -> runMyRouteViewT $ do
150− mapRoutedT (mapSetRouteT appendHead) $ _frontend_head frontend
151− mapRoutedT (mapSetRouteT appendBody) $ _frontend_body frontend
152+ mapRoutedT (mapSetRouteT (mapRouteToUrlT appendHead)) $ _frontend_head frontend
153+ mapRoutedT (mapSetRouteT (mapRouteToUrlT appendBody)) $ _frontend_body frontend
152154
153155renderFrontendHtml
154156 :: (t ~ DomTimeline)
155− => r
156− -> RoutedT t r (SetRouteT t r' (PostBuildT DomTimeline (StaticDomBuilderT DomTimeline (PerformEventT DomTimeline DomHost)))) ()
157− -> RoutedT t r (SetRouteT t r' (PostBuildT DomTimeline (StaticDomBuilderT DomTimeline (PerformEventT DomTimeline DomHost)))) ()
157+ => (r' -> Text)
158+ -> r
159+ -> RoutedT t r (SetRouteT t r' (RouteToUrlT r' (PostBuildT DomTimeline (StaticDomBuilderT DomTimeline (PerformEventT DomTimeline DomHost))))) ()
160+ -> RoutedT t r (SetRouteT t r' (RouteToUrlT r' (PostBuildT DomTimeline (StaticDomBuilderT DomTimeline (PerformEventT DomTimeline DomHost))))) ()
158161 -> IO ByteString
159−renderFrontendHtml route headWidget bodyWidget = do
162+renderFrontendHtml urlEnc route headWidget bodyWidget = do
160163 --TODO: We should probably have a "NullEventWriterT" or a frozen reflex timeline
161− html <- fmap snd $ renderStatic $ fmap fst $ runSetRouteT $ flip runRoutedT (pure route) $
164+ html <- fmap snd $ renderStatic $ fmap fst $ flip runRouteToUrlT urlEnc $ runSetRouteT $ flip runRoutedT (pure route) $
162165 el "html" $ do
163166 el "head" headWidget
164167 el "body" bodyWidget
lib/route/src/Obelisk/Route/Frontend.hs+108−2
@@ -41,6 +41,11 @@ module Obelisk.Route.Frontend
4141 , SetRoute(..)
4242 , runSetRouteT
4343 , mapSetRouteT
44+ , RouteToUrl(..)
45+ , RouteToUrlT(..)
46+ , runRouteToUrlT
47+ , mapRouteToUrlT
48+ , routeLink
4449 ) where
4550
4651import Prelude hiding ((.), id)
@@ -61,6 +66,8 @@ import Data.Constraint (Dict (..))
6166import Data.Dependent.Sum (DSum (..))
6267import Data.GADT.Compare
6368import Data.Monoid
69+import Data.Proxy
70+import Data.Text (Text)
6471import qualified Data.Text as T
6572import Data.Functor.Compose
6673import Reflex.Class
@@ -290,6 +297,85 @@ instance (Monad m, MonadQuery t vs m) => MonadQuery t vs (SetRouteT t r m) where
290297 askQueryResult = lift askQueryResult
291298 queryIncremental = lift . queryIncremental
292299
300+class RouteToUrl r m | m -> r where
301+ askRouteToUrl :: m (r -> Text)
302+
303+newtype RouteToUrlT r m a = RouteToUrlT { unRouteToUrlT :: ReaderT (r -> Text) m a }
304+ deriving (Functor, Applicative, Monad, MonadFix, MonadTrans, NotReady t, MonadHold t, MonadSample t, PostBuild t, TriggerEvent t, MonadIO, MonadReflexCreateTrigger t, HasDocument)
305+
306+runRouteToUrlT
307+ :: RouteToUrlT r m a
308+ -> (r -> Text)
309+ -> m a
310+runRouteToUrlT a = runReaderT (unRouteToUrlT a)
311+
312+mapRouteToUrlT :: (forall x. m x -> n x) -> RouteToUrlT r m a -> RouteToUrlT r n a
313+mapRouteToUrlT f (RouteToUrlT m) = RouteToUrlT $ mapReaderT f m
314+
315+instance Monad m => RouteToUrl r (RouteToUrlT r m) where
316+ askRouteToUrl = RouteToUrlT ask
317+
318+instance (Monad m, RouteToUrl r m) => RouteToUrl r (SetRouteT t r' m) where
319+ askRouteToUrl = lift askRouteToUrl
320+
321+instance (Monad m, RouteToUrl r m) => RouteToUrl r (RoutedT t r' m) where
322+ askRouteToUrl = lift askRouteToUrl
323+
324+instance HasJSContext m => HasJSContext (RouteToUrlT r m) where
325+ type JSContextPhantom (RouteToUrlT r m) = JSContextPhantom m
326+ askJSContext = lift askJSContext
327+
328+instance Prerender js m => Prerender js (RouteToUrlT r m) where
329+ prerenderClientDict = fmap (\Dict -> Dict) (prerenderClientDict :: Maybe (Dict (PrerenderClientConstraint js m)))
330+
331+instance Requester t m => Requester t (RouteToUrlT r m) where
332+ type Request (RouteToUrlT r m) = Request m
333+ type Response (RouteToUrlT r m) = Response m
334+ requesting = RouteToUrlT . requesting
335+ requesting_ = RouteToUrlT . requesting_
336+
337+#ifndef ghcjs_HOST_OS
338+deriving instance MonadJSM m => MonadJSM (RouteToUrlT r m)
339+#endif
340+
341+instance PerformEvent t m => PerformEvent t (RouteToUrlT r m) where
342+ type Performable (RouteToUrlT r m) = Performable m
343+ performEvent = lift . performEvent
344+ performEvent_ = lift . performEvent_
345+
346+instance MonadRef m => MonadRef (RouteToUrlT r m) where
347+ type Ref (RouteToUrlT r m) = Ref m
348+ newRef = lift . newRef
349+ readRef = lift . readRef
350+ writeRef r = lift . writeRef r
351+
352+instance HasJS x m => HasJS x (RouteToUrlT r m) where
353+ type JSX (RouteToUrlT r m) = JSX m
354+ liftJS = lift . liftJS
355+
356+instance MonadTransControl (RouteToUrlT r) where
357+ type StT (RouteToUrlT r) a = StT (ReaderT (r -> Text)) a
358+ liftWith = defaultLiftWith RouteToUrlT unRouteToUrlT
359+ restoreT = defaultRestoreT RouteToUrlT
360+
361+instance PrimMonad m => PrimMonad (RouteToUrlT r m ) where
362+ type PrimState (RouteToUrlT r m) = PrimState m
363+ primitive = lift . primitive
364+
365+instance DomBuilder t m => DomBuilder t (RouteToUrlT r m) where
366+ type DomBuilderSpace (RouteToUrlT r m) = DomBuilderSpace m
367+
368+instance Adjustable t m => Adjustable t (RouteToUrlT r m) where
369+ runWithReplace a0 a' = RouteToUrlT $ runWithReplace (coerce a0) $ coerceEvent a'
370+ traverseIntMapWithKeyWithAdjust f a0 a' = RouteToUrlT $ traverseIntMapWithKeyWithAdjust (coerce f) (coerce a0) $ coerce a'
371+ traverseDMapWithKeyWithAdjust f a0 a' = RouteToUrlT $ traverseDMapWithKeyWithAdjust (\k v -> coerce $ f k v) (coerce a0) $ coerce a'
372+ traverseDMapWithKeyWithAdjustWithMove f a0 a' = RouteToUrlT $ traverseDMapWithKeyWithAdjustWithMove (\k v -> coerce $ f k v) (coerce a0) $ coerce a'
373+
374+instance (Monad m, MonadQuery t vs m) => MonadQuery t vs (RouteToUrlT r m) where
375+ tellQueryIncremental = lift . tellQueryIncremental
376+ askQueryResult = lift askQueryResult
377+ queryIncremental = lift . queryIncremental
378+
293379runRouteViewT
294380 :: forall t m r a.
295381 ( TriggerEvent t m
@@ -300,7 +386,7 @@ runRouteViewT
300386 , MonadFix m
301387 )
302388 => (Encoder Identity Identity r PageName)
303− -> RoutedT t r (SetRouteT t r m) a
389+ -> RoutedT t r (SetRouteT t r (RouteToUrlT r m)) a
304390 -> m a
305391runRouteViewT routeEncoder a = do
306392 rec historyState <- manageHistory $ HistoryCommand_PushState <$> setState
@@ -313,7 +399,7 @@ runRouteViewT routeEncoder a = do
313399 where
314400 errorLeft (Left e) = error (T.unpack e)
315401 errorLeft (Right x) = x
316− (result, changeState) <- runSetRouteT $ runRoutedT a route
402+ (result, changeState) <- runRouteToUrlT (runSetRouteT $ runRoutedT a route) $ (\(p, q) -> T.pack $ p <> q) . encode theEncoder
317403 let f (currentHistoryState, oldRoute) change =
318404 let newRoute = appEndo change oldRoute
319405 (newPath, newQuery) = encode theEncoder newRoute
@@ -337,6 +423,26 @@ runRouteViewT routeEncoder a = do
337423 setState = attachWith f ((,) <$> current historyState <*> current route) changeState
338424 return result
339425
426+-- | A link widget that, when clicked, sets the route to the provided route. In non-javascript
427+-- contexts, this widget falls back to using @href@s to control navigation
428+routeLink
429+ :: forall t m a route.
430+ ( DomBuilder t m
431+ , RouteToUrl (R route) m
432+ , SetRoute t (R route) m
433+ )
434+ => R route -- ^ Target route
435+ -> m a -- ^ Child widget
436+ -> m a
437+routeLink r w = do
438+ enc <- askRouteToUrl
439+ let cfg = (def :: ElementConfig EventResult t (DomBuilderSpace m))
440+ & elementConfig_eventSpec %~ addEventSpecFlags (Proxy :: Proxy (DomBuilderSpace m)) Click (\_ -> preventDefault)
441+ & elementConfig_initialAttributes .~ "href" =: enc r
442+ (e, a) <- element "a" cfg w
443+ setRoute $ r <$ domEvent Click e
444+ return a
445+
340446-- On ios due to sandboxing when loading the page from a file adapt the
341447-- path to be based on the hash.
342448
lib/run/src/Obelisk/Run.hs+7−6
@@ -82,7 +82,8 @@ run port serveStaticAsset backend frontend = do
8282 getRouteWith validFullEncoder >>= \case
8383 Identity r -> case r of
8484 InL backendRoute :=> Identity a -> serveRoute $ backendRoute :/ a
85− InR obeliskRoute :=> Identity a -> serveDefaultObeliskApp serveStaticAsset frontend $ obeliskRoute :/ a
85+ InR obeliskRoute :=> Identity a ->
86+ serveDefaultObeliskApp (mkRouteToUrl validFullEncoder) serveStaticAsset frontend $ obeliskRoute :/ a
8687 let conf = defRunConfig { _runConfig_redirectPort = port }
8788 runWidget conf frontend validFullEncoder `finally` killThread backendTid
8889
@@ -142,14 +143,14 @@ obeliskApp opts frontend validFullEncoder uri backend = do
142143 { W.pathInfo = fst $ encode jsaddleWarpRouteValidEncoder jsaddleRoute
143144 }
144145 InR (ObeliskRoute_App appRouteComponent) :=> Identity appRouteRest -> do
145− html <- renderJsaddleFrontend (appRouteComponent :/ appRouteRest) frontend
146− sendResponse $ W.responseLBS H.status200 [("Content-Type", "text/html")] $ BSLC.fromStrict html
146+ html <- renderJsaddleFrontend (mkRouteToUrl validFullEncoder) (appRouteComponent :/ appRouteRest) frontend
147+ sendResponse $ W.responseLBS H.status200 [("Content-Type", staticRenderContentType)] $ BSLC.fromStrict html
147148 _ -> backend req sendResponse
148149
149−renderJsaddleFrontend :: route -> Frontend route -> IO ByteString
150−renderJsaddleFrontend r f =
150+renderJsaddleFrontend :: (route -> Text) -> route -> Frontend route -> IO ByteString
151+renderJsaddleFrontend urlEnc r f =
151152 let jsaddleScript = elAttr "script" ("src" =: "/jsaddle/jsaddle.js") blank
152− in renderFrontendHtml r (_frontend_head f >> injectExecutableConfigs) (_frontend_body f >> jsaddleScript)
153+ in renderFrontendHtml urlEnc r (_frontend_head f >> injectExecutableConfigs) (_frontend_body f >> jsaddleScript)
153154
154155-- | like 'bindPortTCP' but reconnects on exception
155156bindPortTCPRetry :: Settings
lib/selftest/src/Obelisk/SelfTest.hs+28−17
@@ -76,16 +76,19 @@ main = do
7676 let verbosity = bool silently verbosely isVerbose
7777 obeliskImpl <- fromString <$> getEnv "OBELISK_IMPL"
7878 httpManager <- HTTP.newManager HTTP.defaultManagerSettings
79+ [p0, p1, p2, p3] <- liftIO $ getFreePorts 4
7980 withSystemTempDirectory "initCache" $ \initCache -> do
8081 -- Setup the ob init cache
8182 void . shellyOb verbosity $ chdir (fromString initCache) $ do
8283 run_ "ob" ["init"]
8384 run_ "git" ["init"]
84− hspec $ do
85+ hspec $ parallel $ do
8586 let shelly_ = void . shellyOb verbosity
8687
8788 inTmp :: (Shelly.FilePath -> Sh a) -> IO ()
88− inTmp f = shelly_ . withSystemTempDirectory "test" $ (chdir <*> f) . fromString
89+ inTmp f = withTmp (chdir <*> f)
90+
91+ withTmp f = shelly_ . withSystemTempDirectory "test" $ f . fromString
8992
9093 inTmpObInit f = inTmp $ \dir -> do
9194 run_ "cp" ["-a", fromString $ initCache <> "/.", toTextIgnore dir]
@@ -108,7 +111,7 @@ main = do
108111
109112 diff a b = run "git" ["diff", a, b]
110113
111− describe "ob init" $ do
114+ describe "ob init" $ parallel $ do
112115 it "works with default impl" $ inTmp $ \_ -> run "ob" ["init"]
113116 it "works with master branch impl" $ inTmp $ \_ -> run "ob" ["init", "--branch", "master"]
114117 it "works with symlink" $ inTmp $ \_ -> run "ob" ["init", "--symlink", obeliskImpl]
@@ -128,20 +131,20 @@ main = do
128131
129132 -- These tests fail with "Could not find module 'Obelisk.Generated.Static'"
130133 -- when not run by 'nix-build --attr selftest'
131− describe "ob run" $ do
134+ describe "ob run" $ parallel $ do
132135 it "works in root directory" $ inTmpObInit $ \_ -> do
133− testObRunInDir Nothing httpManager
136+ testObRunInDir p0 p1 Nothing httpManager
134137 it "works in sub directory" $ inTmpObInit $ \_ -> do
135− testObRunInDir (Just "frontend") httpManager
138+ testObRunInDir p2 p3 (Just "frontend") httpManager
136139
137− describe "obelisk project" $ do
140+ describe "obelisk project" $ parallel $ do
138141 it "can build obelisk command" $ inTmpObInit $ \_ -> run "nix-build" ["-A", "command" , obeliskImpl]
139142 it "can build obelisk skeleton" $ inTmpObInit $ \_ -> run "nix-build" ["-A", "skeleton", obeliskImpl]
140143 it "can build obelisk shell" $ inTmpObInit $ \_ -> run "nix-build" ["-A", "shell", obeliskImpl]
141144 -- See https://github.com/obsidiansystems/obelisk/issues/101
142145 -- it "can build everything" $ shelly_ $ run "nix-build" [obeliskImpl]
143146
144− describe "blank initialized project" $ do
147+ describe "blank initialized project" $ parallel $ do
145148
146149 it "can build ghc.backend" $ inTmpObInit $ \_ -> do
147150 run "nix-build" ["--no-out-link", "-A", "ghc.backend"]
@@ -167,7 +170,7 @@ main = do
167170 uu <- update
168171 assertRevEQ u uu
169172
170− describe "ob thunk pack/unpack" $ do
173+ describe "ob thunk pack/unpack" $ parallel $ do
171174 it "has thunk pack and unpack inverses" $ inTmpObInit $ \_ -> do
172175
173176 e <- commitAll
@@ -180,6 +183,14 @@ main = do
180183 assertRevEQ eu eupu
181184 assertRevNE e eu
182185
186+ it "unpacks the correct branch" $ withTmp $ \dir -> do
187+ let branch = "master"
188+ run_ "git" ["clone", "https://github.com/reflex-frp/reflex.git", toTextIgnore dir, "--branch", branch]
189+ run_ "ob" ["thunk", "pack", toTextIgnore dir]
190+ run_ "ob" ["thunk", "unpack", toTextIgnore dir]
191+ branch' <- chdir dir $ run "git" ["rev-parse", "--abbrev-ref", "HEAD"]
192+ liftIO $ assertEqual "" branch (T.strip branch')
193+
183194 it "can pack and unpack plain git repos" $ do
184195 shelly_ $ withSystemTempDirectory "git-repo" $ \dir -> do
185196 let repo = toTextIgnore $ dir </> ("repo" :: String)
@@ -203,14 +214,13 @@ main = do
203214 testThunkPack (dir </> thunk)
204215
205216-- | Run `ob run` in the given directory (maximum of one level deep)
206−testObRunInDir :: Maybe Shelly.FilePath -> HTTP.Manager -> Sh ()
207−testObRunInDir mdir httpManager = handle_sh (\case ExitSuccess -> pure (); e -> throw e) $ do
217+testObRunInDir :: Socket.PortNumber -> Socket.PortNumber -> Maybe Shelly.FilePath -> HTTP.Manager -> Sh ()
218+testObRunInDir p0 p1 mdir httpManager = handle_sh (\case ExitSuccess -> pure (); e -> throw e) $ do
208219 let uri p = "http://localhost:" <> T.pack (show p) <> "/" -- trailing slash required for comparison
209− writefile "config/common/route" . uri =<< liftIO getFreePort -- Use a free port initially
220+ writefile "config/common/route" $ uri p0
210221 maybe id chdir mdir $ runHandle "ob" ["run"] $ \stdout -> do
211− freePort <- liftIO getFreePort
212222 firstUri <- handleObRunStdout httpManager stdout
213− let newUri = uri freePort
223+ let newUri = uri p1
214224 when (firstUri == newUri) $ errorExit $
215225 "Startup URI (" <> firstUri <> ") is the same as test URI (" <> newUri <> ")"
216226 maybe id (\_ -> chdir "..") mdir $ alterRouteTo newUri stdout
@@ -285,10 +295,11 @@ obRunCheck httpManager _stdout frontendUri = do
285295 req frontendUri >>= \r -> when (HTTP.responseStatus r /= HTTP.ok200) $ errorExit $
286296 "Request to frontend server failed: " <> T.pack (show r)
287297
288−getFreePort :: IO Socket.PortNumber
289−getFreePort = Socket.withSocketsDo $ do
298+getFreePorts :: Int -> IO [Socket.PortNumber]
299+getFreePorts 0 = pure []
300+getFreePorts n = Socket.withSocketsDo $ do
290301 addr:_ <- Socket.getAddrInfo (Just Socket.defaultHints) (Just "127.0.0.1") (Just "0")
291− bracket (open addr) Socket.close Socket.socketPort
302+ bracket (open addr) Socket.close $ \s -> (:) <$> Socket.socketPort s <*> getFreePorts (n - 1)
292303 where
293304 open addr = do
294305 sock <- Socket.socket (Socket.addrFamily addr) (Socket.addrSocketType addr) (Socket.addrProtocol addr)
lib/snap/obelisk-snap.cabaldeleted−40
@@ -1,40 +0,0 @@
1−Name: obelisk-snap
2−Version: 0.1
3−Synopsis: Project Synopsis Here
4−Description: Project Description Here
5−License: BSD3
6−Author: Obsidian Systems
7−Maintainer: maintainer@obsidian.systems
8−Stability: Experimental
9−Category: Web
10−Build-type: Simple
11−Cabal-version: >=1.2
12−
13−library
14− hs-source-dirs: src
15−
16− build-depends:
17− base,
18− bytestring,
19− data-default,
20− diagrams-lib,
21− diagrams-svg,
22− filepath,
23− lens,
24− lucid,
25− monad-control,
26− obelisk-asset-serve-snap,
27− obelisk-snap-extras,
28− semigroups,
29− raw-strings-qq,
30− snap,
31− snap-core,
32− svg-builder,
33− text,
34− transformers-base
35−
36− exposed-modules:
37− Obelisk.Snap
38−
39− other-extensions: TemplateHaskell
40− ghc-options: -threaded -Wall -fno-warn-unused-do-bind -fwarn-tabs -funbox-strict-fields -O2 -fprof-auto-calls -rtsopts
lib/snap/src/Obelisk/Snap.hsdeleted−99
@@ -1,99 +0,0 @@
1−{-# LANGUAGE TemplateHaskell #-}
2−{-# LANGUAGE QuasiQuotes #-}
3−{-# LANGUAGE OverloadedStrings #-}
4−
5−module Obelisk.Snap where
6−
7−import Obelisk.Asset.Serve.Snap
8−import Obelisk.Snap.Extras
9−
10−import Snap
11−
12−import Control.Lens
13−import Data.ByteString (ByteString)
14−import Data.Default
15−import Data.Monoid
16−import qualified Data.Text as T
17−import Lucid
18−import System.FilePath
19−import Control.Monad.IO.Class
20−
21−-- Data type for web app configuration
22−data AppConfig m
23− = AppConfig { _appConfig_initialBody :: m ByteString
24− , _appConfig_initialHead :: ByteString
25− , _appConfig_serveJsexe :: Bool
26− , _appConfig_jsexe :: FilePath
27− }
28−
29−-- Default instance for app configuration
30−instance Monad m => Default (AppConfig m) where
31− def = AppConfig { _appConfig_initialBody = return mempty
32− , _appConfig_initialHead = mempty
33− , _appConfig_serveJsexe = True
34− , _appConfig_jsexe = "frontend.jsexe"
35− }
36−
37−{- | Takes a location, app, and an app configuration as arguements and
38− routes the request to the correct handler. If "appConfig_serveJsexe"
39− returns "True", additional js paths and asset paths will be appended to
40− handler. Otherwise, it will return "404 Not Found" -}
41−serveAppAt :: MonadSnap m => ByteString -> FilePath -> AppConfig m -> m ()
42−serveAppAt loc app cfg = do
43− route $ [ (loc, ifTop $ serveStaticIndex cfg)
44− , (loc, serveAssets (app </> "static.assets") (app </> "static"))
45− , (loc <> "/version", doNotCache >> serveFileIfExistsAs "text/plain" (app </> "version"))
46− ]
47− ++ if _appConfig_serveJsexe cfg
48− then [(loc, serveAssets (app </> frontendJsAssetsPath cfg) (app </> frontendJsPath cfg))]
49− else []
50− ++ [ (loc, doNotCache >> error404) ]
51−
52−-- Helper function used in 'serveAppAt', writes a 404 error message in ByteString
53−error404 :: MonadSnap m => m ()
54−error404 = do
55− modifyResponse $ setResponseCode 404
56− writeBS "404 Not Found"
57−
58−-- Partially applied 'serveAppAt', specialized to the root directory
59−serveApp :: MonadSnap m => FilePath -> AppConfig m -> m ()
60−serveApp = serveAppAt ""
61−
62−-- Helper function used in 'serveAppAt', returns a frontendJs/... filepath
63−frontendJsPath :: AppConfig m -> FilePath
64−frontendJsPath (AppConfig { _appConfig_jsexe = jsexe }) = "frontendJs" </> jsexe
65−
66−-- Helper function used in 'serveAppAt', returns a frontendJs.assets/... filepath
67−frontendJsAssetsPath :: AppConfig m -> FilePath
68−frontendJsAssetsPath (AppConfig { _appConfig_jsexe = jsexe }) = "frontendJs.assets" </> jsexe
69−
70−-- Helper funtion used in 'serveAppAt', writes a lazy bytestring to the body of Http response
71−serveStaticIndex :: MonadSnap m => AppConfig m -> m ()
72−serveStaticIndex cfg = do
73− -- Decode, pack, and append asset target to file path
74− appJsPath <- liftIO $ getAssetPath (frontendJsAssetsPath cfg) "/all.js"
75− initialBody <- _appConfig_initialBody cfg
76− -- Render and write html head and body to response
77− writeLBS $ renderBS $ doctypehtml_ $ do
78− head_ $ do
79− meta_ [charset_ "utf-8"] -- meta-data charset description
80− meta_ [name_ "viewport", content_ "width=device-width, initial-scale=1.0"] -- meta-data viewport description
81− toHtmlRaw $ _appConfig_initialHead cfg
82− body_ $ do -- <body>
83− toHtmlRaw initialBody -- HtmlT monad wrapper
84− script_ [type_ "application/javascript", src_ (maybe "/all.js" T.pack appJsPath), defer_ "defer"] ("" :: String)
85−
86−{- | Takes an AppConfig monad and uses it to generate & write Lazy ByteString
87− to the body of the https response. This one comes with hard coded values
88− for the logo -}
89−serveIndex :: MonadSnap m => AppConfig m -> m ()
90−serveIndex cfg = do
91− appJsPath <- liftIO $ getAssetPath (frontendJsAssetsPath cfg) "all.js"
92− writeLBS $ renderBS $ doctypehtml_ $ do
93− head_ $ do
94− meta_ [charset_ "utf-8"]
95− meta_ [name_ "viewport", content_ "width=device-width, initial-scale=1.0"]
96− body_ $ do
97− script_ [type_ "application/javascript", src_ (maybe "/all.js" T.pack appJsPath), defer_ "defer"] ("" :: String)
98−
99−makeLenses ''AppConfig
release.nix−1
@@ -23,7 +23,6 @@ let
2323 "obelisk-run"
2424 "obelisk-route"
2525 "obelisk-selftest"
26− "obelisk-snap"
2726 "obelisk-snap-extras"
2827 ];
2928