@@ -14,25 +14,20 @@ module Obelisk.Command.Run where
14import Control.Arrow ((&&&))
14import Control.Arrow ((&&&))
15import Control.Exception (Exception, bracket)
15import Control.Exception (Exception, bracket)
16import Control.Lens (ifor, (.~), (&))
16import Control.Lens (ifor, (.~), (&))
17−import Control.Monad (filterM)
17+import Control.Monad (filterM, unless, void)
18import Control.Monad.Except (runExceptT, throwError)
18import Control.Monad.Except (runExceptT, throwError)
19import Control.Monad.IO.Class (liftIO)
19import Control.Monad.IO.Class (liftIO)
20import Control.Monad.Reader (MonadIO)
20import Control.Monad.Reader (MonadIO)
21−import Data.Bifoldable (bifoldr1)
22−import Data.Bifunctor (bimap)
23import Data.Coerce (coerce)
21import Data.Coerce (coerce)
24import Data.Default (def)
22import Data.Default (def)
25import Data.Either (partitionEithers)
23import Data.Either (partitionEithers)
26import Data.Foldable (fold, for_, toList)
24import Data.Foldable (fold, for_, toList)
27import Data.Functor.Identity (runIdentity)
25import Data.Functor.Identity (runIdentity)
28−import Data.List (intercalate)
29import Data.List.NonEmpty (NonEmpty)
26import Data.List.NonEmpty (NonEmpty)
30import qualified Data.List.NonEmpty as NE
27import qualified Data.List.NonEmpty as NE
31import Data.Map (Map)
28import Data.Map (Map)
32import qualified Data.Map as Map
29import qualified Data.Map as Map
33−import qualified Data.Map.Monoidal as MMap
30+import Data.Maybe
34−import Data.Maybe (catMaybes, fromMaybe, mapMaybe)
35−import Data.Ord (comparing)
36import Data.Set (Set)
31import Data.Set (Set)
37import qualified Data.Set as Set
32import qualified Data.Set as Set
38import Data.String.Here.Interpolated (i)
33import Data.String.Here.Interpolated (i)
@@ -46,17 +41,17 @@ import Distribution.Compiler (CompilerFlavor(..))
46import Distribution.PackageDescription.Parsec (parseGenericPackageDescription)
41import Distribution.PackageDescription.Parsec (parseGenericPackageDescription)
47import Distribution.Parsec.ParseResult (runParseResult)
42import Distribution.Parsec.ParseResult (runParseResult)
48import qualified Distribution.System as Dist
43import qualified Distribution.System as Dist
49−import Distribution.Types.BuildInfo (buildable, cppOptions, defaultExtensions, defaultLanguage, hsSourceDirs, options)
44+import Distribution.Types.BuildInfo
50−import Distribution.Types.CondTree (simplifyCondTree)
45+import Distribution.Types.CondTree
51−import Distribution.Types.GenericPackageDescription (ConfVar (Arch, Impl, OS), condLibrary)
46+import Distribution.Types.GenericPackageDescription
52−import Distribution.Types.Library (libBuildInfo)
47+import Distribution.Types.Library
53−import Distribution.Utils.Generic (toUTF8BS, readUTF8File)
48+import Distribution.Utils.Generic
54import qualified Distribution.Parsec.Common as Dist
49import qualified Distribution.Parsec.Common as Dist
55import qualified Hpack.Config as Hpack
50import qualified Hpack.Config as Hpack
56import qualified Hpack.Render as Hpack
51import qualified Hpack.Render as Hpack
57import qualified Hpack.Yaml as Hpack
52import qualified Hpack.Yaml as Hpack
58−import Language.Haskell.Extension (Extension, Language)
53+import Language.Haskell.Extension
59−import qualified Network.Socket as Socket
54+import Network.Socket hiding (Debug)
60import System.Directory
55import System.Directory
61import System.Environment (getExecutablePath)
56import System.Environment (getExecutablePath)
62import System.FilePath
57import System.FilePath
@@ -66,18 +61,19 @@ import System.IO.Temp (withSystemTempDirectory)
66import Obelisk.App (MonadObelisk)
61import Obelisk.App (MonadObelisk)
67import Obelisk.CliApp (
62import Obelisk.CliApp (
68 Severity (..),
63 Severity (..),
72 readCreateProcessWithExitCode,
68 readCreateProcessWithExitCode,
73 readProcessAndLogStderr,
69 readProcessAndLogStderr,
76 setDelegateCtlc,
71 setDelegateCtlc,
77 withSpinner,
73 withSpinner,
79import Obelisk.Command.Nix
75import Obelisk.Command.Nix
80−import Obelisk.Command.Project (nixShellWithoutPkgs, withProjectRoot, findProjectAssets, bashEscape)
76+import Obelisk.Command.Project (nixShellWithPkgs, withProjectRoot, findProjectAssets)
81import Obelisk.Command.Thunk (attrCacheFileName)
77import Obelisk.Command.Thunk (attrCacheFileName)
82import Obelisk.Command.Utils (findExePath, ghcidExePath)
78import Obelisk.Command.Utils (findExePath, ghcidExePath)
@@ -94,17 +90,10 @@ data CabalPackageInfo = CabalPackageInfo
94 -- ^ List of globally set languages of the library component
90 -- ^ List of globally set languages of the library component
95 , _cabalPackageInfo_compilerOptions :: [(CompilerFlavor, [String])]
91 , _cabalPackageInfo_compilerOptions :: [(CompilerFlavor, [String])]
96 -- ^ List of compiler-specific options (e.g., the "ghc-options" field of the cabal file)
92 -- ^ List of compiler-specific options (e.g., the "ghc-options" field of the cabal file)
97− , _cabalPackageInfo_cppOptions :: [String]
98− -- ^ List of CPP (C Preprocessor) options (e.g. the "cpp-options" field of the cabal file)
101−-- | 'Bool' with a better name for its purpose.
95+-- | 'Bool' with a better name for it's purpose.
102−data Interpret = Interpret_Interpret | Interpret_NoInterpret deriving (Eq, Ord, Show)
96+data HackOn = HackOn_HackOn | HackOn_NoHackOn deriving (Eq, Ord, Show)
104−textInterpret :: Interpret -> Text
105−textInterpret = \case
106− Interpret_Interpret -> "Interpret"
107− Interpret_NoInterpret -> "NoInterpret"
109-- | Describe a set of 'FilePath's as a tree to facilitate merging them in a convenient way.
98-- | Describe a set of 'FilePath's as a tree to facilitate merging them in a convenient way.
110data PathTree a = PathTree_Node
99data PathTree a = PathTree_Node
@@ -112,16 +101,8 @@ data PathTree a = PathTree_Node
112 (Map FilePath (PathTree a)) -- Branches to deeper leaves
101 (Map FilePath (PathTree a)) -- Branches to deeper leaves
113 deriving (Eq, Ord, Show, Functor, Foldable, Traversable)
102 deriving (Eq, Ord, Show, Functor, Foldable, Traversable)
115−-- | 2D ASCII drawing of a 'PathTree'. Adapted from Data.Tree.draw.
104+emptyPathTree :: PathTree a
116−drawPathTree :: (a -> Text) -> PathTree a -> Text
105+emptyPathTree = PathTree_Node Nothing mempty
117−drawPathTree showA (PathTree_Node _ ts0) = T.intercalate "\n" $ goForest (Map.toList ts0)
119− annotated ma = maybe id (\a b -> b <> " [" <> showA a <> "]") ma . T.pack
120− goTree (fp, PathTree_Node ma forest) = annotated ma fp : goForest (Map.toList forest)
122− goForest [tree] = shift "└─ " " " (goTree tree)
123− goForest (tree:forest) = shift "├─ " "│ " (goTree tree) <> goForest forest
124− shift first other = zipWith (<>) (first : repeat other)
126-- | Used to signal to obelisk that it's being invoked as a preprocessor
107-- | Used to signal to obelisk that it's being invoked as a preprocessor
127preprocessorIdentifier :: String
108preprocessorIdentifier :: String
@@ -151,7 +132,7 @@ profile profileBasePattern rtsFlags = withProjectRoot "." $ \root -> do
151 liftIO $ createDirectoryIfMissing True $ takeDirectory $ root </> profileBaseName
132 liftIO $ createDirectoryIfMissing True $ takeDirectory $ root </> profileBaseName
152 putLog Debug $ "Storing profiled data under base name of " <> T.pack (root </> profileBaseName)
133 putLog Debug $ "Storing profiled data under base name of " <> T.pack (root </> profileBaseName)
153 freePort <- getFreePort
134 freePort <- getFreePort
154− runProcess_ $ setCwd (Just root) $ setDelegateCtlc True $ proc (outPath </> "bin" </> "ob-run") $
135+ (_, _, _, ph) <- createProcess_ "runProfExe" $ setCwd (Just root) $ setDelegateCtlc True $ proc (outPath </> "bin" </> "ob-run") $
155 [ show freePort
136 [ show freePort
156 , T.unpack assets
137 , T.unpack assets
157 , profileBaseName
138 , profileBaseName
@@ -159,16 +140,16 @@ profile profileBasePattern rtsFlags = withProjectRoot "." $ \root -> do
159 , "-po" <> profileBaseName
140 , "-po" <> profileBaseName
160 ] <> rtsFlags
141 ] <> rtsFlags
161 <> [ "-RTS" ]
142 <> [ "-RTS" ]
162−
143+ void $ waitForProcess ph
163−run :: MonadObelisk m => FilePath -> PathTree Interpret -> m ()
145+run :: MonadObelisk m => FilePath -> PathTree HackOn -> m ()
164−run root interpretPaths = do
146+run root hackPaths = do
165− pkgs <- getParsedLocalPkgs root interpretPaths
147+ pkgs <- getParsedLocalPkgs root hackPaths
148+ withGhciScript pkgs root $ \dotGhciPath -> do
149+ freePort <- getFreePort
166− assets <- findProjectAssets root
150+ assets <- findProjectAssets root
167− putLog Debug $ "Assets impurely loaded from: " <> assets
151+ putLog Debug $ "Assets impurely loaded from: " <> assets
168− ghciArgs <- getGhciSessionSettings pkgs root True
169− freePort <- getFreePort
170− withGhciScriptArgs pkgs $ \dotGhciArgs -> do
171− runGhcid root True (ghciArgs <> dotGhciArgs) pkgs $ Just $ unwords
152+ runGhcid root True dotGhciPath pkgs $ Just $ unwords
172 [ "Obelisk.Run.run"
153 [ "Obelisk.Run.run"
173 , show freePort
154 , show freePort
174 , "(Obelisk.Run.runServeAsset " ++ show assets ++ ")"
155 , "(Obelisk.Run.runServeAsset " ++ show assets ++ ")"
@@ -176,55 +157,51 @@ run root interpretPaths = do
176 , "Frontend.frontend"
157 , "Frontend.frontend"
179−runRepl :: MonadObelisk m => FilePath -> PathTree Interpret -> m ()
160+runRepl :: MonadObelisk m => FilePath -> PathTree HackOn -> m ()
180−runRepl root interpretPaths = do
161+runRepl root hackPaths = do
181− pkgs <- getParsedLocalPkgs root interpretPaths
162+ pkgs <- getParsedLocalPkgs root hackPaths
182− ghciArgs <- getGhciSessionSettings pkgs "." True
163+ withGhciScript pkgs "." $ \dotGhciPath ->
183− withGhciScriptArgs pkgs $ \dotGhciArgs ->
184− runGhciRepl root pkgs (ghciArgs <> dotGhciArgs)
164+ runGhciRepl root pkgs dotGhciPath
186−runWatch :: MonadObelisk m => FilePath -> PathTree Interpret -> m ()
166+runWatch :: MonadObelisk m => FilePath -> PathTree HackOn -> m ()
187−runWatch root interpretPaths = do
167+runWatch root hackPaths = do
188− pkgs <- getParsedLocalPkgs root interpretPaths
168+ pkgs <- getParsedLocalPkgs root hackPaths
189− ghciArgs <- getGhciSessionSettings pkgs root True
169+ withGhciScript pkgs root $ \dotGhciPath ->
190− withGhciScriptArgs pkgs $ \dotGhciArgs ->
191− runGhcid root True (ghciArgs <> dotGhciArgs) pkgs Nothing
170+ runGhcid root True dotGhciPath pkgs Nothing
193−exportGhciConfig :: MonadObelisk m => Bool -> FilePath -> PathTree Interpret -> m [String]
172+exportGhciConfig :: MonadObelisk m => FilePath -> PathTree HackOn -> m [String]
194−exportGhciConfig useRelativePaths root interpretPaths = do
173+exportGhciConfig root hackPaths = do
195− pkgs <- getParsedLocalPkgs root interpretPaths
174+ pkgs <- getParsedLocalPkgs root hackPaths
196− getGhciSessionSettings pkgs "." useRelativePaths
175+ getGhciSessionSettings pkgs "."
198−nixShellForInterpretPaths :: MonadObelisk m => Bool -> String -> FilePath -> PathTree Interpret -> Maybe String -> m ()
177+nixShellForHackPaths :: MonadObelisk m => Bool -> String -> FilePath -> PathTree HackOn -> Maybe String -> m ()
199−nixShellForInterpretPaths isPure shell root interpretPaths cmd = do
178+nixShellForHackPaths isPure shell root hackPaths cmd = do
200− pkgs <- getParsedLocalPkgs root interpretPaths
179+ pkgs <- getParsedLocalPkgs root hackPaths
201− nixShellWithoutPkgs root isPure False (packageInfoToNamePathMap pkgs) shell cmd
180+ nixShellWithPkgs root isPure False (packageInfoToNamePathMap pkgs) shell cmd
203-- | Like 'getLocalPkgs' but also parses them and fails if any of them can't be parsed.
182-- | Like 'getLocalPkgs' but also parses them and fails if any of them can't be parsed.
204−getParsedLocalPkgs :: MonadObelisk m => FilePath -> PathTree Interpret -> m (NonEmpty CabalPackageInfo)
183+getParsedLocalPkgs :: MonadObelisk m => FilePath -> PathTree HackOn -> m (NonEmpty CabalPackageInfo)
205−getParsedLocalPkgs root interpretPaths = parsePackagesOrFail =<< getLocalPkgs root interpretPaths
184+getParsedLocalPkgs root hackPaths = parsePackagesOrFail =<< getLocalPkgs root hackPaths
207-- | Relative paths to local packages of an obelisk project.
186-- | Relative paths to local packages of an obelisk project.
209-- These are a combination of the obelisk predefined local packages,
188-- These are a combination of the obelisk predefined local packages,
210-- and any packages that the user has set with the @packages@ argument
189-- and any packages that the user has set with the @packages@ argument
211-- to the Nix @project@ function.
190-- to the Nix @project@ function.
212−getLocalPkgs :: forall m. MonadObelisk m => FilePath -> PathTree Interpret -> m (Set FilePath)
191+getLocalPkgs :: forall m. MonadObelisk m => FilePath -> PathTree HackOn -> m (Set FilePath)
213−getLocalPkgs root interpretPaths = do
192+getLocalPkgs root hackPaths = do
214− putLog Debug $ [i|Finding packages with root ${root} and interpret paths:|] <> "\n" <> drawPathTree textInterpret interpretPaths
193+ putLog Debug [i|Finding packages with root ${root} and hacking paths ${hackPaths}|]
215 obeliskPackagePaths <- runFind ["-L", root, "-name", ".obelisk", "-type", "d"]
194 obeliskPackagePaths <- runFind ["-L", root, "-name", ".obelisk", "-type", "d"]
217 -- We do not want to find packages that are embedded inside other obelisk projects, unless that
196 -- We do not want to find packages that are embedded inside other obelisk projects, unless that
218 -- obelisk project is our own.
197 -- obelisk project is our own.
219− obeliskPackageExclusions <- liftIO $ fmap Set.fromList $ traverse canonicalizePath $
220− filter (/= root) $ map takeDirectory obeliskPackagePaths
198+ let obeliskPackageExclusions = Set.fromList $ filter (/= root) $ map takeDirectory obeliskPackagePaths
221− putLog Debug [i|Excluding obelisk packages: ${T.pack $ unwords $ Set.toList obeliskPackageExclusions}|]
199+ rootsAndExclusions = calcHackOnFinds "" hackPaths
222− let rootsAndExclusions = calcIntepretFinds "" interpretPaths
224− fmap fold $ for (MMap.toAscList rootsAndExclusions) $ \(interpretPathRoot, exclusions) ->
201+ fmap fold $ for (Map.toAscList rootsAndExclusions) $ \(hackPathRoot, exclusions) ->
225 let allExclusions = obeliskPackageExclusions <> exclusions <> Set.singleton ("*" </> attrCacheFileName)
202 let allExclusions = obeliskPackageExclusions <> exclusions <> Set.singleton ("*" </> attrCacheFileName)
226 in fmap (Set.fromList . map normalise) $ runFind $
203 in fmap (Set.fromList . map normalise) $ runFind $
227− ["-L", interpretPathRoot, "(", "-name", "*.cabal", "-o", "-name", Hpack.packageConfig, ")", "-a", "-type", "f"]
204+ ["-L", hackPathRoot, "(", "-name", "*.cabal", "-o", "-name", Hpack.packageConfig, ")", "-a", "-type", "f"]
228 <> concat [["-not", "-path", p </> "*"] | p <- toList allExclusions]
205 <> concat [["-not", "-path", p </> "*"] | p <- toList allExclusions]
230 runFind args = do
207 runFind args = do
@@ -234,15 +211,15 @@ getLocalPkgs root interpretPaths = do
235-- | Calculates a set of root 'FilePath's along with each one's corresponding set of exclusions.
212-- | Calculates a set of root 'FilePath's along with each one's corresponding set of exclusions.
236-- This is used when constructing a set of @find@ commands to run to produce a set of packages
213-- This is used when constructing a set of @find@ commands to run to produce a set of packages
237−-- that matches the user's @--interpret@/@--no-interpret@ settings.
214+-- that matches the user's @--hack-on@/@--no-hack-on@ settings.
238−calcIntepretFinds :: FilePath -> PathTree Interpret -> MMap.MonoidalMap FilePath (Set FilePath)
215+calcHackOnFinds :: FilePath -> PathTree HackOn -> Map FilePath (Set FilePath)
239−calcIntepretFinds treeRoot0 tree0 = runIdentity $ go treeRoot0 tree0
216+calcHackOnFinds treeRoot0 tree0 = runIdentity $ go treeRoot0 tree0
241− go treeRoot tree = foldPathTreeFor (== Interpret_Interpret) treeRoot tree $ \parent children -> do
218+ go treeRoot tree = foldPathTreeFor (== HackOn_HackOn) treeRoot tree $ \parent children -> do
242− exclusions <- foldPathTreeFor (== Interpret_NoInterpret) parent children $ \parent' children' ->
219+ exclusions <- foldPathTreeFor (== HackOn_NoHackOn) parent children $ \parent' children' ->
243 pure $ Map.singleton parent' children'
220 pure $ Map.singleton parent' children'
244− deeperFinds <- Map.traverseWithKey go exclusions
221+ deeperFinds <- fmap fold $ Map.traverseWithKey go exclusions
245− pure $ MMap.singleton parent (Map.keysSet exclusions) <> fold (MMap.MonoidalMap deeperFinds)
222+ pure $ Map.singleton parent (Map.keysSet exclusions) <> deeperFinds
247-- | Traverses a 'PathTree' and folds all leaves matching a given predicate.
224-- | Traverses a 'PathTree' and folds all leaves matching a given predicate.
248foldPathTreeFor
225foldPathTreeFor
@@ -304,16 +281,15 @@ parseCabalPackage
304 -> m (Maybe CabalPackageInfo)
281 -> m (Maybe CabalPackageInfo)
305parseCabalPackage dir = parseCabalPackage' dir >>= \case
282parseCabalPackage dir = parseCabalPackage' dir >>= \case
306 Left err -> Nothing <$ putLog Error err
283 Left err -> Nothing <$ putLog Error err
307− Right (Just (warnings, pkgInfo)) -> do
284+ Right (warnings, pkgInfo) -> do
308 for_ warnings $ putLog Warning . T.pack . show
285 for_ warnings $ putLog Warning . T.pack . show
309 pure $ Just pkgInfo
286 pure $ Just pkgInfo
310− Right Nothing -> pure Nothing
312-- | Like 'parseCabalPackage' but returns errors and warnings directly so as to avoid 'MonadObelisk'.
288-- | Like 'parseCabalPackage' but returns errors and warnings directly so as to avoid 'MonadObelisk'.
313parseCabalPackage'
289parseCabalPackage'
314 :: (MonadIO m)
290 :: (MonadIO m)
315 => FilePath -- ^ Package directory
291 => FilePath -- ^ Package directory
316− -> m (Either T.Text (Maybe ([Dist.PWarning], CabalPackageInfo)))
292+ -> m (Either T.Text ([Dist.PWarning], CabalPackageInfo))
317parseCabalPackage' pkg = runExceptT $ do
293parseCabalPackage' pkg = runExceptT $ do
318 (cabalContents, packageFile, packageName) <- guessCabalPackageFile pkg >>= \case
294 (cabalContents, packageFile, packageName) <- guessCabalPackageFile pkg >>= \case
319 Left GuessPackageFileError_NotFound -> throwError $ "No .cabal or package.yaml file found in " <> T.pack pkg
295 Left GuessPackageFileError_NotFound -> throwError $ "No .cabal or package.yaml file found in " <> T.pack pkg
@@ -341,7 +317,7 @@ parseCabalPackage' pkg = runExceptT $ do
341 case condLibrary <$> result of
317 case condLibrary <$> result of
342 Right (Just condLib) -> do
318 Right (Just condLib) -> do
343 let (_, lib) = simplifyCondTree evalConfVar condLib
319 let (_, lib) = simplifyCondTree evalConfVar condLib
344− pure $ Just $ (warnings,) $ CabalPackageInfo
320+ pure $ (warnings,) $ CabalPackageInfo
345 { _cabalPackageInfo_packageName = T.pack packageName
321 { _cabalPackageInfo_packageName = T.pack packageName
346 , _cabalPackageInfo_packageFile = packageFile
322 , _cabalPackageInfo_packageFile = packageFile
347 , _cabalPackageInfo_packageRoot = takeDirectory packageFile
323 , _cabalPackageInfo_packageRoot = takeDirectory packageFile
@@ -353,19 +329,18 @@ parseCabalPackage' pkg = runExceptT $ do
353 , _cabalPackageInfo_defaultLanguage =
329 , _cabalPackageInfo_defaultLanguage =
354 defaultLanguage $ libBuildInfo lib
330 defaultLanguage $ libBuildInfo lib
355 , _cabalPackageInfo_compilerOptions = options $ libBuildInfo lib
331 , _cabalPackageInfo_compilerOptions = options $ libBuildInfo lib
356− , _cabalPackageInfo_cppOptions = cppOptions $ libBuildInfo lib
358− Right Nothing -> pure Nothing
333+ Right Nothing -> throwError "Haskell package has no library component"
359 Left (_, errors) ->
334 Left (_, errors) ->
360 throwError $ T.pack $ "Failed to parse " <> packageFile <> ":\n" <> unlines (map show errors)
335 throwError $ T.pack $ "Failed to parse " <> packageFile <> ":\n" <> unlines (map show errors)
362parsePackagesOrFail :: (MonadObelisk m, Foldable f) => f FilePath -> m (NE.NonEmpty CabalPackageInfo)
337parsePackagesOrFail :: (MonadObelisk m, Foldable f) => f FilePath -> m (NE.NonEmpty CabalPackageInfo)
363parsePackagesOrFail dirs' = do
338parsePackagesOrFail dirs' = do
364− packageInfos' <- fmap catMaybes $ for dirs $ \dir -> do
339+ (pkgDirErrs, packageInfos') <- fmap partitionEithers $ for dirs $ \dir -> do
365 flip fmap (parseCabalPackage dir) $ \case
340 flip fmap (parseCabalPackage dir) $ \case
366 Just packageInfo
341 Just packageInfo
367− | _cabalPackageInfo_buildable packageInfo -> Just packageInfo
342+ | _cabalPackageInfo_buildable packageInfo -> Right packageInfo
368− _ -> Nothing
343+ _ -> Left dir
370 -- Sort duplicate packages such that we prefer shorter paths, but fall back to alphabetical ordering.
345 -- Sort duplicate packages such that we prefer shorter paths, but fall back to alphabetical ordering.
371 let packagesByName = Map.map (NE.sortBy $ comparing $ \p -> let n = _cabalPackageInfo_packageFile p in (length n, n))
346 let packagesByName = Map.map (NE.sortBy $ comparing $ \p -> let n = _cabalPackageInfo_packageFile p in (length n, n))
@@ -387,6 +362,9 @@ parsePackagesOrFail dirs' = do
387 "No valid, buildable packages found" <> (if null dirs then "" else " in " <> intercalate ", " dirs)
362 "No valid, buildable packages found" <> (if null dirs then "" else " in " <> intercalate ", " dirs)
388 Just xs -> pure xs
363 Just xs -> pure xs
365+ unless (null pkgDirErrs) $
366+ putLog Warning $ T.pack $ "Failed to find buildable packages in " <> intercalate ", " pkgDirErrs
390 pure packageInfos
368 pure packageInfos
392 dirs = toList dirs'
370 dirs = toList dirs'
@@ -394,129 +372,104 @@ parsePackagesOrFail dirs' = do
394packageInfoToNamePathMap :: Foldable f => f CabalPackageInfo -> Map Text FilePath
372packageInfoToNamePathMap :: Foldable f => f CabalPackageInfo -> Map Text FilePath
395packageInfoToNamePathMap = Map.fromList . map (_cabalPackageInfo_packageName &&& _cabalPackageInfo_packageRoot) . toList
373packageInfoToNamePathMap = Map.fromList . map (_cabalPackageInfo_packageName &&& _cabalPackageInfo_packageRoot) . toList
397−-- Like 'withGhciScript' but provides the precise ghci arguments to add to a ghci session
399− :: (MonadObelisk m, Foldable f)
400− => f CabalPackageInfo -- ^ List of packages to load into ghci
401− -> ([String] -> m ()) -- ^ Action to run with the extra ghci arguments
403−withGhciScriptArgs packageInfos f = withGhciScript loadPreludeManually packageInfos $ \fp -> f ["-XNoImplicitPrelude", "-ghci-script", fp]
405− -- These lines must be first and allow the session to support a custom Prelude when @-XNoImplicitPrelude@
406− -- is passed to the ghci session.
407− loadPreludeManually =
408− [ ":add Prelude" -- @:add@ is used because it's less noisy when there is no custom Prelude
409− , ":set -XImplicitPrelude" -- Turn the default setting on
412-- | Create ghci configuration to load the given packages
375-- | Create ghci configuration to load the given packages
413withGhciScript
376withGhciScript
414 :: (MonadObelisk m, Foldable f)
377 :: (MonadObelisk m, Foldable f)
415− => [String] -- ^ Commands to prefix to file
416− -> f CabalPackageInfo -- ^ List of packages to load into ghci
378+ => f CabalPackageInfo -- ^ List of packages to load into ghci
379+ -> FilePath -- ^ All paths written to the .ghci file will be relative to this path
417 -> (FilePath -> m ()) -- ^ Action to run with the path to generated temporary .ghci
380 -> (FilePath -> m ()) -- ^ Action to run with the path to generated temporary .ghci
419−withGhciScript preCommands (toList -> packageInfos) f =
382+withGhciScript (toList -> packageInfos) pathBase f = do
420− withSystemTempDirectory "ob-ghci" $ \fp -> do
383+ ghciSettings <- getGhciSessionSettings packageInfos pathBase
421− let dotGhciPath = fp </> ".ghci"
384+ let
422− liftIO $ writeFile dotGhciPath dotGhci
425 packageNames = Set.fromList $ map _cabalPackageInfo_packageName packageInfos
385 packageNames = Set.fromList $ map _cabalPackageInfo_packageName packageInfos
426 modulesToLoad = mconcat
386 modulesToLoad = mconcat
427 [ [ "Obelisk.Run" | "obelisk-run" `Set.member` packageNames ]
387 [ [ "Obelisk.Run" | "obelisk-run" `Set.member` packageNames ]
428 , [ "Backend" | "backend" `Set.member` packageNames ]
388 , [ "Backend" | "backend" `Set.member` packageNames ]
429 , [ "Frontend" | "frontend" `Set.member` packageNames ]
389 , [ "Frontend" | "frontend" `Set.member` packageNames ]
431− dotGhci = unlines $
391+ dotGhci = unlines
432− preCommands <>
392+ [ ":set " <> unwords ghciSettings -- TODO: Shell escape
433− [ if null modulesToLoad then "" else ":load " <> unwords modulesToLoad
393+ , if null modulesToLoad then "" else ":load " <> unwords modulesToLoad
434 , "import qualified Obelisk.Run"
394 , "import qualified Obelisk.Run"
435 , "import qualified Frontend"
395 , "import qualified Frontend"
436− , "import qualified Backend"
396+ , "import qualified Backend" ]
437− ]
397+ withSystemTempDirectory "ob-ghci" $ \fp -> do
398+ let dotGhciPath = fp </> ".ghci"
399+ liftIO $ writeFile dotGhciPath dotGhci
439-- | Builds a list of options to pass to ghci or set in .ghci file that configures
402-- | Builds a list of options to pass to ghci or set in .ghci file that configures
440-- the preprocessor and source includes.
403-- the preprocessor and source includes.
441getGhciSessionSettings
404getGhciSessionSettings
442 :: (MonadObelisk m, Foldable f)
405 :: (MonadObelisk m, Foldable f)
443 => f CabalPackageInfo -- ^ List of packages to load into ghci
406 => f CabalPackageInfo -- ^ List of packages to load into ghci
444− -> FilePath -- ^ All paths will be relative to this path
407+ -> FilePath -- ^ All paths written to the .ghci file will be relative to this path
445− -> Bool -- ^ Use relative paths
446 -> m [String]
408 -> m [String]
447−getGhciSessionSettings (toList -> packageInfos) pathBase useRelativePaths = do
409+getGhciSessionSettings (toList -> packageInfos) pathBase = do
448− -- N.B. ghci settings do NOT support escaping in any way. To minimize the likelihood that
449− -- paths-with-spaces ruin our day, we first canonicalize everything, and then relativize
450− -- all paths to 'pathBase'.
451− selfExe <- liftIO $ canonicalizePath =<< getExecutablePath
410+ selfExe <- liftIO getExecutablePath
452− canonicalPathBase <- liftIO $ canonicalizePath pathBase
411+ -- TODO: Shell escape
454− (pkgFiles, pkgSrcPaths :: [NonEmpty FilePath]) <- fmap unzip $ liftIO $ for packageInfos $ \pkg -> do
455− canonicalSrcDirs <- traverse canonicalizePath $ (_cabalPackageInfo_packageRoot pkg </>) <$> _cabalPackageInfo_sourceDirs pkg
456− canonicalPkgFile <- canonicalizePath $ _cabalPackageInfo_packageFile pkg
457− pure (canonicalPkgFile `relativeTo'` canonicalPathBase, (`relativeTo'` canonicalPathBase) <$> canonicalSrcDirs)
461− <> ["-F", "-pgmF", selfExe, "-optF", preprocessorIdentifier]
413+ $ ["-F", "-pgmF", selfExe, "-optF", preprocessorIdentifier]
462− <> concatMap (\p -> ["-optF", p]) pkgFiles
414+ <> concatMap (\p -> ["-optF", makeRelative pathBase $ _cabalPackageInfo_packageFile p]) packageInfos
463− <> [ "-i" <> intercalate ":" (concatMap toList pkgSrcPaths) ]
415+ <> [ "-i" <> intercalate ":" (packageInfos >>= rootedSourceDirs) ]
465− relativeTo' = if useRelativePaths then relativeTo else const
417+ rootedSourceDirs pkg = NE.toList $
466−
418+ makeRelative pathBase . (_cabalPackageInfo_packageRoot pkg </>) <$> _cabalPackageInfo_sourceDirs pkg
467−baseGhciOptions :: [String]
469− [ "-ignore-dot-ghci"
470− , "-no-user-package-db"
471− , "-package-env", "-"
474-- | Run ghci repl
420-- | Run ghci repl
475runGhciRepl
421runGhciRepl
476 :: (MonadObelisk m, Foldable f)
422 :: (MonadObelisk m, Foldable f)
477 => FilePath -- ^ Path to project root
423 => FilePath -- ^ Path to project root
478− -> f CabalPackageInfo -- ^ Packages to keep unbuilt
424+ -> f CabalPackageInfo
479− -> [String] -- ^ GHCi arguments
425+ -> FilePath -- ^ Path to .ghci
481−runGhciRepl root (toList -> packages) ghciArgs =
427+runGhciRepl root (toList -> packages) dotGhci =
482 -- NOTE: We do *not* want to use $(staticWhich "ghci") here because we need the
428 -- NOTE: We do *not* want to use $(staticWhich "ghci") here because we need the
483 -- ghc that is provided by the shell in the user's project.
429 -- ghc that is provided by the shell in the user's project.
484− nixShellWithoutPkgs root True False (packageInfoToNamePathMap packages) "ghc" $
430+ nixShellWithPkgs root True False (packageInfoToNamePathMap packages) "ghc" $ Just $ "ghci " <> makeBaseGhciOptions dotGhci -- TODO: Shell escape
485− Just $ unwords $ fmap bashEscape $ "ghci" : ghciArgs
487-- | Run ghcid
432-- | Run ghcid
489 :: (MonadObelisk m, Foldable f)
434 :: (MonadObelisk m, Foldable f)
490 => FilePath -- ^ Path to project root
435 => FilePath -- ^ Path to project root
491 -> Bool -- ^ Should we chdir to root when running this process?
436 -> Bool -- ^ Should we chdir to root when running this process?
492− -> [String] -- ^ GHCi arguments
437+ -> FilePath -- ^ Path to .ghci
493− -> f CabalPackageInfo -- ^ Packages to keep unbuilt
438+ -> f CabalPackageInfo
494 -> Maybe String -- ^ Optional command to run at every reload
439 -> Maybe String -- ^ Optional command to run at every reload
496−runGhcid root chdirToRoot ghciArgs (toList -> packages) mcmd =
441+runGhcid root chdirToRoot dotGhci (toList -> packages) mcmd =
497− nixShellWithoutPkgs root True chdirToRoot (packageInfoToNamePathMap packages) "ghc" $
442+ nixShellWithPkgs root True chdirToRoot (packageInfoToNamePathMap packages) "ghc" $ Just $ unwords $ ghcidExePath : opts -- TODO: Shell escape
498− Just $ unwords $ fmap bashEscape $ ghcidExePath : opts
500− opts = concat
444+ opts =
446+ , "--command='ghci -ignore-dot-ghci " <> makeBaseGhciOptions dotGhci <> "' "
502− , ["--outputfile=ghcid-output.txt"]
447+ , "--outputfile=ghcid-output.txt"
503− , map (\x -> "--reload=" <> x) reloadFiles
448+ ] <> map (\x -> "--reload='" <> x <> "'") reloadFiles
504− , map (\x -> "--restart=" <> x) restartFiles
449+ <> map (\x -> "--restart='" <> x <> "'") restartFiles
505− , maybe [] (\cmd -> ["--test=" <> cmd]) mcmd
450+ <> testCmd
506− , ["--command=" <> unwords ("ghci" : ghciArgs)]
451+ testCmd = maybeToList (flip fmap mcmd $ \cmd -> "--test='" <> cmd <> "'") -- TODO: Shell escape
508 adjustRoot x = if chdirToRoot then makeRelative root x else x
453 adjustRoot x = if chdirToRoot then makeRelative root x else x
509 reloadFiles = map adjustRoot [root </> "config"]
454 reloadFiles = map adjustRoot [root </> "config"]
510 restartFiles = map (adjustRoot . _cabalPackageInfo_packageFile) packages
455 restartFiles = map (adjustRoot . _cabalPackageInfo_packageFile) packages
457+makeBaseGhciOptions :: FilePath -> String
458+makeBaseGhciOptions dotGhci =
460+ [ "-no-user-package-db"
462+ , "-ghci-script " <> dotGhci
512−getFreePort :: MonadIO m => m Socket.PortNumber
465+getFreePort :: MonadIO m => m PortNumber
513−getFreePort = liftIO $ Socket.withSocketsDo $ do
466+getFreePort = liftIO $ withSocketsDo $ do
514− addr:_ <- Socket.getAddrInfo (Just Socket.defaultHints) (Just "127.0.0.1") (Just "0")
467+ addr:_ <- getAddrInfo (Just defaultHints) (Just "127.0.0.1") (Just "0")
515− bracket (open addr) Socket.close Socket.socketPort
468+ bracket (open addr) close socketPort
517 open addr = do
470 open addr = do
518− sock <- Socket.socket (Socket.addrFamily addr) (Socket.addrSocketType addr) (Socket.addrProtocol addr)
471+ sock <- socket (addrFamily addr) (addrSocketType addr) (addrProtocol addr)
519− Socket.bind sock (Socket.addrAddress addr)
472+ bind sock (addrAddress addr)
520 return sock
473 return sock
@@ -526,29 +479,3 @@ pathToTree a p = go $ splitDirectories p
527 go [] = PathTree_Node (Just a) mempty
480 go [] = PathTree_Node (Just a) mempty
528 go (x : xs) = PathTree_Node Nothing $ Map.singleton x $ go xs
481 go (x : xs) = PathTree_Node Nothing $ Map.singleton x $ go xs
530−-- | Like 'zipWith' but pads with a padding value instead of stopping on the shortest list.
531−zipDefaultWith :: a -> b -> (a -> b -> c) -> [a] -> [b] -> [c]
532−zipDefaultWith _da _db _f [] [] = []
533−zipDefaultWith da db f (a:as) [] = f a db : zipDefaultWith da db f as []
534−zipDefaultWith da db f [] (b:bs) = f da b : zipDefaultWith da db f [] bs
535−zipDefaultWith da db f (a:as) (b:bs) = f a b : zipDefaultWith da db f as bs
537−-- | Makes the first absolute path relative to the second absolute path.
539−-- Both input paths MUST be absolute.
541−-- Unlike 'makeRelative' this does not merely strip prefixes. It will introduce
542−-- enough @..@ paths to make the resulting path truly relative in virtually every
543−-- case. The only exception is on Windows when the two paths are on different
544−-- drives. In this case the resulting path may be absolute.
545−relativeTo :: FilePath -> FilePath -> FilePath
548− $ bimap (collapse . (".." <$) . catMaybes) (collapse . catMaybes)
550− $ dropWhile (\(a,b) -> a == b)
551− $ zipDefaultWith Nothing Nothing (,)
552− (map Just $ splitDirectories base)
553− (map Just $ splitDirectories dir)
554− where collapse = foldr (</>) ""