@@ -14,20 +14,25 @@ module Obelisk.Command.Run where
1414import Control.Arrow ((&&&))
1515import Control.Exception (Exception, bracket)
1616import Control.Lens (ifor, (.~), (&))
17−import Control.Monad (filterM, unless, void)
17+import Control.Monad (filterM)
1818import Control.Monad.Except (runExceptT, throwError)
1919import Control.Monad.IO.Class (liftIO)
2020import Control.Monad.Reader (MonadIO)
21+import Data.Bifoldable (bifoldr1)
22+import Data.Bifunctor (bimap)
2123import Data.Coerce (coerce)
2224import Data.Default (def)
2325import Data.Either (partitionEithers)
2426import Data.Foldable (fold, for_, toList)
2527import Data.Functor.Identity (runIdentity)
28+import Data.List (intercalate)
2629import Data.List.NonEmpty (NonEmpty)
2730import qualified Data.List.NonEmpty as NE
2831import Data.Map (Map)
2932import qualified Data.Map as Map
30−import Data.Maybe
33+import qualified Data.Map.Monoidal as MMap
34+import Data.Maybe (catMaybes, fromMaybe, mapMaybe)
35+import Data.Ord (comparing)
3136import Data.Set (Set)
3237import qualified Data.Set as Set
3338import Data.String.Here.Interpolated (i)
@@ -41,17 +46,17 @@ import Distribution.Compiler (CompilerFlavor(..))
4146import Distribution.PackageDescription.Parsec (parseGenericPackageDescription)
4247import Distribution.Parsec.ParseResult (runParseResult)
4348import qualified Distribution.System as Dist
44−import Distribution.Types.BuildInfo
45−import Distribution.Types.CondTree
46−import Distribution.Types.GenericPackageDescription
47−import Distribution.Types.Library
48−import Distribution.Utils.Generic
49+import Distribution.Types.BuildInfo (buildable, cppOptions, defaultExtensions, defaultLanguage, hsSourceDirs, options)
50+import Distribution.Types.CondTree (simplifyCondTree)
51+import Distribution.Types.GenericPackageDescription (ConfVar (Arch, Impl, OS), condLibrary)
52+import Distribution.Types.Library (libBuildInfo)
53+import Distribution.Utils.Generic (toUTF8BS, readUTF8File)
4954import qualified Distribution.Parsec.Common as Dist
5055import qualified Hpack.Config as Hpack
5156import qualified Hpack.Render as Hpack
5257import qualified Hpack.Yaml as Hpack
53−import Language.Haskell.Extension
54−import Network.Socket hiding (Debug)
58+import Language.Haskell.Extension (Extension, Language)
59+import qualified Network.Socket as Socket
5560import System.Directory
5661import System.Environment (getExecutablePath)
5762import System.FilePath
@@ -61,19 +66,18 @@ import System.IO.Temp (withSystemTempDirectory)
6166import Obelisk.App (MonadObelisk)
6267import Obelisk.CliApp (
6368 Severity (..),
64− createProcess_,
6569 failWith,
6670 proc,
6771 putLog,
6872 readCreateProcessWithExitCode,
6973 readProcessAndLogStderr,
74+ runProcess_,
7075 setCwd,
7176 setDelegateCtlc,
72− waitForProcess,
7377 withSpinner,
7478 )
7579import Obelisk.Command.Nix
76−import Obelisk.Command.Project (nixShellWithPkgs, withProjectRoot, findProjectAssets)
80+import Obelisk.Command.Project (nixShellWithoutPkgs, withProjectRoot, findProjectAssets, bashEscape)
7781import Obelisk.Command.Thunk (attrCacheFileName)
7882import Obelisk.Command.Utils (findExePath, ghcidExePath)
7983
@@ -90,10 +94,17 @@ data CabalPackageInfo = CabalPackageInfo
9094 -- ^ List of globally set languages of the library component
9195 , _cabalPackageInfo_compilerOptions :: [(CompilerFlavor, [String])]
9296 -- ^ 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)
9399 }
94100
95−-- | 'Bool' with a better name for it's purpose.
96−data HackOn = HackOn_HackOn | HackOn_NoHackOn deriving (Eq, Ord, Show)
101+-- | 'Bool' with a better name for its purpose.
102+data Interpret = Interpret_Interpret | Interpret_NoInterpret deriving (Eq, Ord, Show)
103+
104+textInterpret :: Interpret -> Text
105+textInterpret = \case
106+ Interpret_Interpret -> "Interpret"
107+ Interpret_NoInterpret -> "NoInterpret"
97108
98109-- | Describe a set of 'FilePath's as a tree to facilitate merging them in a convenient way.
99110data PathTree a = PathTree_Node
@@ -101,8 +112,16 @@ data PathTree a = PathTree_Node
101112 (Map FilePath (PathTree a)) -- Branches to deeper leaves
102113 deriving (Eq, Ord, Show, Functor, Foldable, Traversable)
103114
104−emptyPathTree :: PathTree a
105−emptyPathTree = PathTree_Node Nothing mempty
115+-- | 2D ASCII drawing of a 'PathTree'. Adapted from Data.Tree.draw.
116+drawPathTree :: (a -> Text) -> PathTree a -> Text
117+drawPathTree showA (PathTree_Node _ ts0) = T.intercalate "\n" $ goForest (Map.toList ts0)
118+ where
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)
121+ goForest [] = []
122+ goForest [tree] = shift "└─ " " " (goTree tree)
123+ goForest (tree:forest) = shift "├─ " "│ " (goTree tree) <> goForest forest
124+ shift first other = zipWith (<>) (first : repeat other)
106125
107126-- | Used to signal to obelisk that it's being invoked as a preprocessor
108127preprocessorIdentifier :: String
@@ -132,7 +151,7 @@ profile profileBasePattern rtsFlags = withProjectRoot "." $ \root -> do
132151 liftIO $ createDirectoryIfMissing True $ takeDirectory $ root </> profileBaseName
133152 putLog Debug $ "Storing profiled data under base name of " <> T.pack (root </> profileBaseName)
134153 freePort <- getFreePort
135− (_, _, _, ph) <- createProcess_ "runProfExe" $ setCwd (Just root) $ setDelegateCtlc True $ proc (outPath </> "bin" </> "ob-run") $
154+ runProcess_ $ setCwd (Just root) $ setDelegateCtlc True $ proc (outPath </> "bin" </> "ob-run") $
136155 [ show freePort
137156 , T.unpack assets
138157 , profileBaseName
@@ -140,16 +159,16 @@ profile profileBasePattern rtsFlags = withProjectRoot "." $ \root -> do
140159 , "-po" <> profileBaseName
141160 ] <> rtsFlags
142161 <> [ "-RTS" ]
143− void $ waitForProcess ph
144−
145−run :: MonadObelisk m => FilePath -> PathTree HackOn -> m ()
146−run root hackPaths = do
147− pkgs <- getParsedLocalPkgs root hackPaths
148− withGhciScript pkgs root $ \dotGhciPath -> do
149− freePort <- getFreePort
150− assets <- findProjectAssets root
151− putLog Debug $ "Assets impurely loaded from: " <> assets
152− runGhcid root True dotGhciPath pkgs $ Just $ unwords
162+
163+run :: MonadObelisk m => FilePath -> PathTree Interpret -> m ()
164+run root interpretPaths = do
165+ pkgs <- getParsedLocalPkgs root interpretPaths
166+ assets <- findProjectAssets root
167+ 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
153172 [ "Obelisk.Run.run"
154173 , show freePort
155174 , "(Obelisk.Run.runServeAsset " ++ show assets ++ ")"
@@ -157,51 +176,55 @@ run root hackPaths = do
157176 , "Frontend.frontend"
158177 ]
159178
160−runRepl :: MonadObelisk m => FilePath -> PathTree HackOn -> m ()
161−runRepl root hackPaths = do
162− pkgs <- getParsedLocalPkgs root hackPaths
163− withGhciScript pkgs "." $ \dotGhciPath ->
164− runGhciRepl root pkgs dotGhciPath
165−
166−runWatch :: MonadObelisk m => FilePath -> PathTree HackOn -> m ()
167−runWatch root hackPaths = do
168− pkgs <- getParsedLocalPkgs root hackPaths
169− withGhciScript pkgs root $ \dotGhciPath ->
170− runGhcid root True dotGhciPath pkgs Nothing
171−
172−exportGhciConfig :: MonadObelisk m => FilePath -> PathTree HackOn -> m [String]
173−exportGhciConfig root hackPaths = do
174− pkgs <- getParsedLocalPkgs root hackPaths
175− getGhciSessionSettings pkgs "."
176−
177−nixShellForHackPaths :: MonadObelisk m => Bool -> String -> FilePath -> PathTree HackOn -> Maybe String -> m ()
178−nixShellForHackPaths isPure shell root hackPaths cmd = do
179− pkgs <- getParsedLocalPkgs root hackPaths
180− nixShellWithPkgs root isPure False (packageInfoToNamePathMap pkgs) shell cmd
179+runRepl :: MonadObelisk m => FilePath -> PathTree Interpret -> m ()
180+runRepl root interpretPaths = do
181+ pkgs <- getParsedLocalPkgs root interpretPaths
182+ ghciArgs <- getGhciSessionSettings pkgs "." True
183+ withGhciScriptArgs pkgs $ \dotGhciArgs ->
184+ runGhciRepl root pkgs (ghciArgs <> dotGhciArgs)
185+
186+runWatch :: MonadObelisk m => FilePath -> PathTree Interpret -> m ()
187+runWatch root interpretPaths = do
188+ pkgs <- getParsedLocalPkgs root interpretPaths
189+ ghciArgs <- getGhciSessionSettings pkgs root True
190+ withGhciScriptArgs pkgs $ \dotGhciArgs ->
191+ runGhcid root True (ghciArgs <> dotGhciArgs) pkgs Nothing
192+
193+exportGhciConfig :: MonadObelisk m => Bool -> FilePath -> PathTree Interpret -> m [String]
194+exportGhciConfig useRelativePaths root interpretPaths = do
195+ pkgs <- getParsedLocalPkgs root interpretPaths
196+ getGhciSessionSettings pkgs "." useRelativePaths
197+
198+nixShellForInterpretPaths :: MonadObelisk m => Bool -> String -> FilePath -> PathTree Interpret -> Maybe String -> m ()
199+nixShellForInterpretPaths isPure shell root interpretPaths cmd = do
200+ pkgs <- getParsedLocalPkgs root interpretPaths
201+ nixShellWithoutPkgs root isPure False (packageInfoToNamePathMap pkgs) shell cmd
181202
182203-- | Like 'getLocalPkgs' but also parses them and fails if any of them can't be parsed.
183−getParsedLocalPkgs :: MonadObelisk m => FilePath -> PathTree HackOn -> m (NonEmpty CabalPackageInfo)
184−getParsedLocalPkgs root hackPaths = parsePackagesOrFail =<< getLocalPkgs root hackPaths
204+getParsedLocalPkgs :: MonadObelisk m => FilePath -> PathTree Interpret -> m (NonEmpty CabalPackageInfo)
205+getParsedLocalPkgs root interpretPaths = parsePackagesOrFail =<< getLocalPkgs root interpretPaths
185206
186207-- | Relative paths to local packages of an obelisk project.
187208--
188209-- These are a combination of the obelisk predefined local packages,
189210-- and any packages that the user has set with the @packages@ argument
190211-- to the Nix @project@ function.
191−getLocalPkgs :: forall m. MonadObelisk m => FilePath -> PathTree HackOn -> m (Set FilePath)
192−getLocalPkgs root hackPaths = do
193− putLog Debug [i|Finding packages with root ${root} and hacking paths ${hackPaths}|]
212+getLocalPkgs :: forall m. MonadObelisk m => FilePath -> PathTree Interpret -> m (Set FilePath)
213+getLocalPkgs root interpretPaths = do
214+ putLog Debug $ [i|Finding packages with root ${root} and interpret paths:|] <> "\n" <> drawPathTree textInterpret interpretPaths
194215 obeliskPackagePaths <- runFind ["-L", root, "-name", ".obelisk", "-type", "d"]
195216
196217 -- We do not want to find packages that are embedded inside other obelisk projects, unless that
197218 -- obelisk project is our own.
198− let obeliskPackageExclusions = Set.fromList $ filter (/= root) $ map takeDirectory obeliskPackagePaths
199− rootsAndExclusions = calcHackOnFinds "" hackPaths
219+ obeliskPackageExclusions <- liftIO $ fmap Set.fromList $ traverse canonicalizePath $
220+ filter (/= root) $ map takeDirectory obeliskPackagePaths
221+ putLog Debug [i|Excluding obelisk packages: ${T.pack $ unwords $ Set.toList obeliskPackageExclusions}|]
222+ let rootsAndExclusions = calcIntepretFinds "" interpretPaths
200223
201− fmap fold $ for (Map.toAscList rootsAndExclusions) $ \(hackPathRoot, exclusions) ->
224+ fmap fold $ for (MMap.toAscList rootsAndExclusions) $ \(interpretPathRoot, exclusions) ->
202225 let allExclusions = obeliskPackageExclusions <> exclusions <> Set.singleton ("*" </> attrCacheFileName)
203226 in fmap (Set.fromList . map normalise) $ runFind $
204− ["-L", hackPathRoot, "(", "-name", "*.cabal", "-o", "-name", Hpack.packageConfig, ")", "-a", "-type", "f"]
227+ ["-L", interpretPathRoot, "(", "-name", "*.cabal", "-o", "-name", Hpack.packageConfig, ")", "-a", "-type", "f"]
205228 <> concat [["-not", "-path", p </> "*"] | p <- toList allExclusions]
206229 where
207230 runFind args = do
@@ -211,15 +234,15 @@ getLocalPkgs root hackPaths = do
211234
212235-- | Calculates a set of root 'FilePath's along with each one's corresponding set of exclusions.
213236-- This is used when constructing a set of @find@ commands to run to produce a set of packages
214−-- that matches the user's @--hack-on@/@--no-hack-on@ settings.
215−calcHackOnFinds :: FilePath -> PathTree HackOn -> Map FilePath (Set FilePath)
216−calcHackOnFinds treeRoot0 tree0 = runIdentity $ go treeRoot0 tree0
237+-- that matches the user's @--interpret@/@--no-interpret@ settings.
238+calcIntepretFinds :: FilePath -> PathTree Interpret -> MMap.MonoidalMap FilePath (Set FilePath)
239+calcIntepretFinds treeRoot0 tree0 = runIdentity $ go treeRoot0 tree0
217240 where
218− go treeRoot tree = foldPathTreeFor (== HackOn_HackOn) treeRoot tree $ \parent children -> do
219− exclusions <- foldPathTreeFor (== HackOn_NoHackOn) parent children $ \parent' children' ->
241+ go treeRoot tree = foldPathTreeFor (== Interpret_Interpret) treeRoot tree $ \parent children -> do
242+ exclusions <- foldPathTreeFor (== Interpret_NoInterpret) parent children $ \parent' children' ->
220243 pure $ Map.singleton parent' children'
221− deeperFinds <- fmap fold $ Map.traverseWithKey go exclusions
222− pure $ Map.singleton parent (Map.keysSet exclusions) <> deeperFinds
244+ deeperFinds <- Map.traverseWithKey go exclusions
245+ pure $ MMap.singleton parent (Map.keysSet exclusions) <> fold (MMap.MonoidalMap deeperFinds)
223246
224247-- | Traverses a 'PathTree' and folds all leaves matching a given predicate.
225248foldPathTreeFor
@@ -281,15 +304,16 @@ parseCabalPackage
281304 -> m (Maybe CabalPackageInfo)
282305parseCabalPackage dir = parseCabalPackage' dir >>= \case
283306 Left err -> Nothing <$ putLog Error err
284− Right (warnings, pkgInfo) -> do
307+ Right (Just (warnings, pkgInfo)) -> do
285308 for_ warnings $ putLog Warning . T.pack . show
286309 pure $ Just pkgInfo
310+ Right Nothing -> pure Nothing
287311
288312-- | Like 'parseCabalPackage' but returns errors and warnings directly so as to avoid 'MonadObelisk'.
289313parseCabalPackage'
290314 :: (MonadIO m)
291315 => FilePath -- ^ Package directory
292− -> m (Either T.Text ([Dist.PWarning], CabalPackageInfo))
316+ -> m (Either T.Text (Maybe ([Dist.PWarning], CabalPackageInfo)))
293317parseCabalPackage' pkg = runExceptT $ do
294318 (cabalContents, packageFile, packageName) <- guessCabalPackageFile pkg >>= \case
295319 Left GuessPackageFileError_NotFound -> throwError $ "No .cabal or package.yaml file found in " <> T.pack pkg
@@ -317,7 +341,7 @@ parseCabalPackage' pkg = runExceptT $ do
317341 case condLibrary <$> result of
318342 Right (Just condLib) -> do
319343 let (_, lib) = simplifyCondTree evalConfVar condLib
320− pure $ (warnings,) $ CabalPackageInfo
344+ pure $ Just $ (warnings,) $ CabalPackageInfo
321345 { _cabalPackageInfo_packageName = T.pack packageName
322346 , _cabalPackageInfo_packageFile = packageFile
323347 , _cabalPackageInfo_packageRoot = takeDirectory packageFile
@@ -329,18 +353,19 @@ parseCabalPackage' pkg = runExceptT $ do
329353 , _cabalPackageInfo_defaultLanguage =
330354 defaultLanguage $ libBuildInfo lib
331355 , _cabalPackageInfo_compilerOptions = options $ libBuildInfo lib
356+ , _cabalPackageInfo_cppOptions = cppOptions $ libBuildInfo lib
332357 }
333− Right Nothing -> throwError "Haskell package has no library component"
358+ Right Nothing -> pure Nothing
334359 Left (_, errors) ->
335360 throwError $ T.pack $ "Failed to parse " <> packageFile <> ":\n" <> unlines (map show errors)
336361
337362parsePackagesOrFail :: (MonadObelisk m, Foldable f) => f FilePath -> m (NE.NonEmpty CabalPackageInfo)
338363parsePackagesOrFail dirs' = do
339− (pkgDirErrs, packageInfos') <- fmap partitionEithers $ for dirs $ \dir -> do
364+ packageInfos' <- fmap catMaybes $ for dirs $ \dir -> do
340365 flip fmap (parseCabalPackage dir) $ \case
341366 Just packageInfo
342− | _cabalPackageInfo_buildable packageInfo -> Right packageInfo
343− _ -> Left dir
367+ | _cabalPackageInfo_buildable packageInfo -> Just packageInfo
368+ _ -> Nothing
344369
345370 -- Sort duplicate packages such that we prefer shorter paths, but fall back to alphabetical ordering.
346371 let packagesByName = Map.map (NE.sortBy $ comparing $ \p -> let n = _cabalPackageInfo_packageFile p in (length n, n))
@@ -362,9 +387,6 @@ parsePackagesOrFail dirs' = do
362387 "No valid, buildable packages found" <> (if null dirs then "" else " in " <> intercalate ", " dirs)
363388 Just xs -> pure xs
364389
365− unless (null pkgDirErrs) $
366− putLog Warning $ T.pack $ "Failed to find buildable packages in " <> intercalate ", " pkgDirErrs
367−
368390 pure packageInfos
369391 where
370392 dirs = toList dirs'
@@ -372,104 +394,129 @@ parsePackagesOrFail dirs' = do
372394packageInfoToNamePathMap :: Foldable f => f CabalPackageInfo -> Map Text FilePath
373395packageInfoToNamePathMap = Map.fromList . map (_cabalPackageInfo_packageName &&& _cabalPackageInfo_packageRoot) . toList
374396
397+-- Like 'withGhciScript' but provides the precise ghci arguments to add to a ghci session
398+withGhciScriptArgs
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
402+ -> m ()
403+withGhciScriptArgs packageInfos f = withGhciScript loadPreludeManually packageInfos $ \fp -> f ["-XNoImplicitPrelude", "-ghci-script", fp]
404+ where
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
410+ ]
411+
375412-- | Create ghci configuration to load the given packages
376413withGhciScript
377414 :: (MonadObelisk m, Foldable f)
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
415+ => [String] -- ^ Commands to prefix to file
416+ -> f CabalPackageInfo -- ^ List of packages to load into ghci
380417 -> (FilePath -> m ()) -- ^ Action to run with the path to generated temporary .ghci
381418 -> m ()
382−withGhciScript (toList -> packageInfos) pathBase f = do
383− ghciSettings <- getGhciSessionSettings packageInfos pathBase
384− let
419+withGhciScript preCommands (toList -> packageInfos) f =
420+ withSystemTempDirectory "ob-ghci" $ \fp -> do
421+ let dotGhciPath = fp </> ".ghci"
422+ liftIO $ writeFile dotGhciPath dotGhci
423+ f dotGhciPath
424+ where
385425 packageNames = Set.fromList $ map _cabalPackageInfo_packageName packageInfos
386426 modulesToLoad = mconcat
387427 [ [ "Obelisk.Run" | "obelisk-run" `Set.member` packageNames ]
388428 , [ "Backend" | "backend" `Set.member` packageNames ]
389429 , [ "Frontend" | "frontend" `Set.member` packageNames ]
390430 ]
391− dotGhci = unlines
392− [ ":set " <> unwords ghciSettings -- TODO: Shell escape
393− , if null modulesToLoad then "" else ":load " <> unwords modulesToLoad
431+ dotGhci = unlines $
432+ preCommands <>
433+ [ if null modulesToLoad then "" else ":load " <> unwords modulesToLoad
394434 , "import qualified Obelisk.Run"
395435 , "import qualified Frontend"
396− , "import qualified Backend" ]
397− withSystemTempDirectory "ob-ghci" $ \fp -> do
398− let dotGhciPath = fp </> ".ghci"
399− liftIO $ writeFile dotGhciPath dotGhci
400− f dotGhciPath
436+ , "import qualified Backend"
437+ ]
401438
402439-- | Builds a list of options to pass to ghci or set in .ghci file that configures
403440-- the preprocessor and source includes.
404441getGhciSessionSettings
405442 :: (MonadObelisk m, Foldable f)
406443 => f CabalPackageInfo -- ^ List of packages to load into ghci
407− -> FilePath -- ^ All paths written to the .ghci file will be relative to this path
444+ -> FilePath -- ^ All paths will be relative to this path
445+ -> Bool -- ^ Use relative paths
408446 -> m [String]
409−getGhciSessionSettings (toList -> packageInfos) pathBase = do
410− selfExe <- liftIO getExecutablePath
411− -- TODO: Shell escape
447+getGhciSessionSettings (toList -> packageInfos) pathBase useRelativePaths = 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
452+ canonicalPathBase <- liftIO $ canonicalizePath pathBase
453+
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)
458+
412459 pure
413− $ ["-F", "-pgmF", selfExe, "-optF", preprocessorIdentifier]
414− <> concatMap (\p -> ["-optF", makeRelative pathBase $ _cabalPackageInfo_packageFile p]) packageInfos
415− <> [ "-i" <> intercalate ":" (packageInfos >>= rootedSourceDirs) ]
460+ $ baseGhciOptions
461+ <> ["-F", "-pgmF", selfExe, "-optF", preprocessorIdentifier]
462+ <> concatMap (\p -> ["-optF", p]) pkgFiles
463+ <> [ "-i" <> intercalate ":" (concatMap toList pkgSrcPaths) ]
416464 where
417− rootedSourceDirs pkg = NE.toList $
418− makeRelative pathBase . (_cabalPackageInfo_packageRoot pkg </>) <$> _cabalPackageInfo_sourceDirs pkg
465+ relativeTo' = if useRelativePaths then relativeTo else const
466+
467+baseGhciOptions :: [String]
468+baseGhciOptions =
469+ [ "-ignore-dot-ghci"
470+ , "-no-user-package-db"
471+ , "-package-env", "-"
472+ ]
419473
420474-- | Run ghci repl
421475runGhciRepl
422476 :: (MonadObelisk m, Foldable f)
423477 => FilePath -- ^ Path to project root
424− -> f CabalPackageInfo
425− -> FilePath -- ^ Path to .ghci
478+ -> f CabalPackageInfo -- ^ Packages to keep unbuilt
479+ -> [String] -- ^ GHCi arguments
426480 -> m ()
427−runGhciRepl root (toList -> packages) dotGhci =
481+runGhciRepl root (toList -> packages) ghciArgs =
428482 -- NOTE: We do *not* want to use $(staticWhich "ghci") here because we need the
429483 -- ghc that is provided by the shell in the user's project.
430− nixShellWithPkgs root True False (packageInfoToNamePathMap packages) "ghc" $ Just $ "ghci " <> makeBaseGhciOptions dotGhci -- TODO: Shell escape
484+ nixShellWithoutPkgs root True False (packageInfoToNamePathMap packages) "ghc" $
485+ Just $ unwords $ fmap bashEscape $ "ghci" : ghciArgs
431486
432487-- | Run ghcid
433488runGhcid
434489 :: (MonadObelisk m, Foldable f)
435490 => FilePath -- ^ Path to project root
436491 -> Bool -- ^ Should we chdir to root when running this process?
437− -> FilePath -- ^ Path to .ghci
438− -> f CabalPackageInfo
492+ -> [String] -- ^ GHCi arguments
493+ -> f CabalPackageInfo -- ^ Packages to keep unbuilt
439494 -> Maybe String -- ^ Optional command to run at every reload
440495 -> m ()
441−runGhcid root chdirToRoot dotGhci (toList -> packages) mcmd =
442− nixShellWithPkgs root True chdirToRoot (packageInfoToNamePathMap packages) "ghc" $ Just $ unwords $ ghcidExePath : opts -- TODO: Shell escape
496+runGhcid root chdirToRoot ghciArgs (toList -> packages) mcmd =
497+ nixShellWithoutPkgs root True chdirToRoot (packageInfoToNamePathMap packages) "ghc" $
498+ Just $ unwords $ fmap bashEscape $ ghcidExePath : opts
443499 where
444− opts =
445− [ "-W"
446− , "--command='ghci -ignore-dot-ghci " <> makeBaseGhciOptions dotGhci <> "' "
447− , "--outputfile=ghcid-output.txt"
448− ] <> map (\x -> "--reload='" <> x <> "'") reloadFiles
449− <> map (\x -> "--restart='" <> x <> "'") restartFiles
450− <> testCmd
451− testCmd = maybeToList (flip fmap mcmd $ \cmd -> "--test='" <> cmd <> "'") -- TODO: Shell escape
452−
500+ opts = concat
501+ [ ["-W"]
502+ , ["--outputfile=ghcid-output.txt"]
503+ , map (\x -> "--reload=" <> x) reloadFiles
504+ , map (\x -> "--restart=" <> x) restartFiles
505+ , maybe [] (\cmd -> ["--test=" <> cmd]) mcmd
506+ , ["--command=" <> unwords ("ghci" : ghciArgs)]
507+ ]
453508 adjustRoot x = if chdirToRoot then makeRelative root x else x
454509 reloadFiles = map adjustRoot [root </> "config"]
455510 restartFiles = map (adjustRoot . _cabalPackageInfo_packageFile) packages
456511
457−makeBaseGhciOptions :: FilePath -> String
458−makeBaseGhciOptions dotGhci =
459− unwords
460− [ "-no-user-package-db"
461− , "-package-env -"
462− , "-ghci-script " <> dotGhci
463− ]
464−
465−getFreePort :: MonadIO m => m PortNumber
466−getFreePort = liftIO $ withSocketsDo $ do
467− addr:_ <- getAddrInfo (Just defaultHints) (Just "127.0.0.1") (Just "0")
468− bracket (open addr) close socketPort
512+getFreePort :: MonadIO m => m Socket.PortNumber
513+getFreePort = liftIO $ Socket.withSocketsDo $ do
514+ addr:_ <- Socket.getAddrInfo (Just Socket.defaultHints) (Just "127.0.0.1") (Just "0")
515+ bracket (open addr) Socket.close Socket.socketPort
469516 where
470517 open addr = do
471− sock <- socket (addrFamily addr) (addrSocketType addr) (addrProtocol addr)
472− bind sock (addrAddress addr)
518+ sock <- Socket.socket (Socket.addrFamily addr) (Socket.addrSocketType addr) (Socket.addrProtocol addr)
519+ Socket.bind sock (Socket.addrAddress addr)
473520 return sock
474521
475522
@@ -479,3 +526,29 @@ pathToTree a p = go $ splitDirectories p
479526 where
480527 go [] = PathTree_Node (Just a) mempty
481528 go (x : xs) = PathTree_Node Nothing $ Map.singleton x $ go xs
529+
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
536+
537+-- | Makes the first absolute path relative to the second absolute path.
538+--
539+-- Both input paths MUST be absolute.
540+--
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
546+relativeTo dir base
547+ = bifoldr1 (</>)
548+ $ bimap (collapse . (".." <$) . catMaybes) (collapse . catMaybes)
549+ $ unzip
550+ $ dropWhile (\(a,b) -> a == b)
551+ $ zipDefaultWith Nothing Nothing (,)
552+ (map Just $ splitDirectories base)
553+ (map Just $ splitDirectories dir)
554+ where collapse = foldr (</>) ""