@@ -14,7 +14,7 @@ module Obelisk.Command.Run where
1414import Control.Arrow ((&&&))
1515import Control.Exception (Exception, bracket)
1616import Control.Lens (ifor, (.~), (&))
17−import Control.Monad (filterM)
17+import Control.Monad (filterM, unless, void)
1818import Control.Monad.Except (runExceptT, throwError)
1919import Control.Monad.IO.Class (liftIO)
2020import Control.Monad.Reader (MonadIO)
@@ -31,7 +31,7 @@ import qualified Data.List.NonEmpty as NE
3131import Data.Map (Map)
3232import qualified Data.Map as Map
3333import qualified Data.Map.Monoidal as MMap
34−import Data.Maybe (catMaybes, fromMaybe, mapMaybe)
34+import Data.Maybe (catMaybes, fromMaybe, mapMaybe, maybeToList)
3535import Data.Ord (comparing)
3636import Data.Set (Set)
3737import qualified Data.Set as Set
@@ -46,7 +46,7 @@ import Distribution.Compiler (CompilerFlavor(..))
4646import Distribution.PackageDescription.Parsec (parseGenericPackageDescription)
4747import Distribution.Parsec.ParseResult (runParseResult)
4848import qualified Distribution.System as Dist
49−import Distribution.Types.BuildInfo (buildable, cppOptions, defaultExtensions, defaultLanguage, hsSourceDirs, options)
49+import Distribution.Types.BuildInfo (buildable, defaultExtensions, defaultLanguage, hsSourceDirs, options)
5050import Distribution.Types.CondTree (simplifyCondTree)
5151import Distribution.Types.GenericPackageDescription (ConfVar (Arch, Impl, OS), condLibrary)
5252import Distribution.Types.Library (libBuildInfo)
@@ -66,18 +66,19 @@ import System.IO.Temp (withSystemTempDirectory)
6666import Obelisk.App (MonadObelisk)
6767import Obelisk.CliApp (
6868 Severity (..),
69+ createProcess_,
6970 failWith,
7071 proc,
7172 putLog,
7273 readCreateProcessWithExitCode,
7374 readProcessAndLogStderr,
74− runProcess_,
7575 setCwd,
7676 setDelegateCtlc,
77+ waitForProcess,
7778 withSpinner,
7879 )
7980import Obelisk.Command.Nix
80−import Obelisk.Command.Project (nixShellWithoutPkgs, withProjectRoot, findProjectAssets, bashEscape)
81+import Obelisk.Command.Project (nixShellWithoutPkgs, withProjectRoot, findProjectAssets)
8182import Obelisk.Command.Thunk (attrCacheFileName)
8283import Obelisk.Command.Utils (findExePath, ghcidExePath)
8384
@@ -94,11 +95,9 @@ data CabalPackageInfo = CabalPackageInfo
9495 -- ^ List of globally set languages of the library component
9596 , _cabalPackageInfo_compilerOptions :: [(CompilerFlavor, [String])]
9697 -- ^ 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)
9998 }
10099
101−-- | 'Bool' with a better name for its purpose.
100+-- | 'Bool' with a better name for it's purpose.
102101data Interpret = Interpret_Interpret | Interpret_NoInterpret deriving (Eq, Ord, Show)
103102
104103textInterpret :: Interpret -> Text
@@ -151,7 +150,7 @@ profile profileBasePattern rtsFlags = withProjectRoot "." $ \root -> do
151150 liftIO $ createDirectoryIfMissing True $ takeDirectory $ root </> profileBaseName
152151 putLog Debug $ "Storing profiled data under base name of " <> T.pack (root </> profileBaseName)
153152 freePort <- getFreePort
154− runProcess_ $ setCwd (Just root) $ setDelegateCtlc True $ proc (outPath </> "bin" </> "ob-run") $
153+ (_, _, _, ph) <- createProcess_ "runProfExe" $ setCwd (Just root) $ setDelegateCtlc True $ proc (outPath </> "bin" </> "ob-run") $
155154 [ show freePort
156155 , T.unpack assets
157156 , profileBaseName
@@ -159,16 +158,17 @@ profile profileBasePattern rtsFlags = withProjectRoot "." $ \root -> do
159158 , "-po" <> profileBaseName
160159 ] <> rtsFlags
161160 <> [ "-RTS" ]
161+ void $ waitForProcess ph
162162
163163run :: MonadObelisk m => FilePath -> PathTree Interpret -> m ()
164164run root interpretPaths = do
165165 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
166+ withGhciScript pkgs $ \dotGhciPath -> do
167+ assets <- findProjectAssets root
168+ putLog Debug $ "Assets impurely loaded from: " <> assets
169+ ghciArgs <- getGhciSessionSettings pkgs root True
170+ freePort <- getFreePort
171+ runGhcid root True (ghciArgs <> mkGhciScriptArg dotGhciPath) pkgs $ Just $ unwords
172172 [ "Obelisk.Run.run"
173173 , show freePort
174174 , "(Obelisk.Run.runServeAsset " ++ show assets ++ ")"
@@ -180,15 +180,15 @@ runRepl :: MonadObelisk m => FilePath -> PathTree Interpret -> m ()
180180runRepl root interpretPaths = do
181181 pkgs <- getParsedLocalPkgs root interpretPaths
182182 ghciArgs <- getGhciSessionSettings pkgs "." True
183− withGhciScriptArgs pkgs $ \dotGhciArgs ->
184− runGhciRepl root pkgs (ghciArgs <> dotGhciArgs)
183+ withGhciScript pkgs $ \dotGhciPath ->
184+ runGhciRepl root pkgs (ghciArgs <> mkGhciScriptArg dotGhciPath)
185185
186186runWatch :: MonadObelisk m => FilePath -> PathTree Interpret -> m ()
187187runWatch root interpretPaths = do
188188 pkgs <- getParsedLocalPkgs root interpretPaths
189189 ghciArgs <- getGhciSessionSettings pkgs root True
190− withGhciScriptArgs pkgs $ \dotGhciArgs ->
191− runGhcid root True (ghciArgs <> dotGhciArgs) pkgs Nothing
190+ withGhciScript pkgs $ \dotGhciPath ->
191+ runGhcid root True (ghciArgs <> mkGhciScriptArg dotGhciPath) pkgs Nothing
192192
193193exportGhciConfig :: MonadObelisk m => Bool -> FilePath -> PathTree Interpret -> m [String]
194194exportGhciConfig useRelativePaths root interpretPaths = do
@@ -304,16 +304,15 @@ parseCabalPackage
304304 -> m (Maybe CabalPackageInfo)
305305parseCabalPackage dir = parseCabalPackage' dir >>= \case
306306 Left err -> Nothing <$ putLog Error err
307− Right (Just (warnings, pkgInfo)) -> do
307+ Right (warnings, pkgInfo) -> do
308308 for_ warnings $ putLog Warning . T.pack . show
309309 pure $ Just pkgInfo
310− Right Nothing -> pure Nothing
311310
312311-- | Like 'parseCabalPackage' but returns errors and warnings directly so as to avoid 'MonadObelisk'.
313312parseCabalPackage'
314313 :: (MonadIO m)
315314 => FilePath -- ^ Package directory
316− -> m (Either T.Text (Maybe ([Dist.PWarning], CabalPackageInfo)))
315+ -> m (Either T.Text ([Dist.PWarning], CabalPackageInfo))
317316parseCabalPackage' pkg = runExceptT $ do
318317 (cabalContents, packageFile, packageName) <- guessCabalPackageFile pkg >>= \case
319318 Left GuessPackageFileError_NotFound -> throwError $ "No .cabal or package.yaml file found in " <> T.pack pkg
@@ -341,7 +340,7 @@ parseCabalPackage' pkg = runExceptT $ do
341340 case condLibrary <$> result of
342341 Right (Just condLib) -> do
343342 let (_, lib) = simplifyCondTree evalConfVar condLib
344− pure $ Just $ (warnings,) $ CabalPackageInfo
343+ pure $ (warnings,) $ CabalPackageInfo
345344 { _cabalPackageInfo_packageName = T.pack packageName
346345 , _cabalPackageInfo_packageFile = packageFile
347346 , _cabalPackageInfo_packageRoot = takeDirectory packageFile
@@ -353,19 +352,18 @@ parseCabalPackage' pkg = runExceptT $ do
353352 , _cabalPackageInfo_defaultLanguage =
354353 defaultLanguage $ libBuildInfo lib
355354 , _cabalPackageInfo_compilerOptions = options $ libBuildInfo lib
356− , _cabalPackageInfo_cppOptions = cppOptions $ libBuildInfo lib
357355 }
358− Right Nothing -> pure Nothing
356+ Right Nothing -> throwError "Haskell package has no library component"
359357 Left (_, errors) ->
360358 throwError $ T.pack $ "Failed to parse " <> packageFile <> ":\n" <> unlines (map show errors)
361359
362360parsePackagesOrFail :: (MonadObelisk m, Foldable f) => f FilePath -> m (NE.NonEmpty CabalPackageInfo)
363361parsePackagesOrFail dirs' = do
364− packageInfos' <- fmap catMaybes $ for dirs $ \dir -> do
362+ (pkgDirErrs, packageInfos') <- fmap partitionEithers $ for dirs $ \dir -> do
365363 flip fmap (parseCabalPackage dir) $ \case
366364 Just packageInfo
367− | _cabalPackageInfo_buildable packageInfo -> Just packageInfo
368− _ -> Nothing
365+ | _cabalPackageInfo_buildable packageInfo -> Right packageInfo
366+ _ -> Left dir
369367
370368 -- Sort duplicate packages such that we prefer shorter paths, but fall back to alphabetical ordering.
371369 let packagesByName = Map.map (NE.sortBy $ comparing $ \p -> let n = _cabalPackageInfo_packageFile p in (length n, n))
@@ -387,6 +385,9 @@ parsePackagesOrFail dirs' = do
387385 "No valid, buildable packages found" <> (if null dirs then "" else " in " <> intercalate ", " dirs)
388386 Just xs -> pure xs
389387
388+ unless (null pkgDirErrs) $
389+ putLog Warning $ T.pack $ "Failed to find buildable packages in " <> intercalate ", " pkgDirErrs
390+
390391 pure packageInfos
391392 where
392393 dirs = toList dirs'
@@ -394,29 +395,13 @@ parsePackagesOrFail dirs' = do
394395packageInfoToNamePathMap :: Foldable f => f CabalPackageInfo -> Map Text FilePath
395396packageInfoToNamePathMap = Map.fromList . map (_cabalPackageInfo_packageName &&& _cabalPackageInfo_packageRoot) . toList
396397
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−
412398-- | Create ghci configuration to load the given packages
413399withGhciScript
414400 :: (MonadObelisk m, Foldable f)
415− => [String] -- ^ Commands to prefix to file
416− -> f CabalPackageInfo -- ^ List of packages to load into ghci
401+ => f CabalPackageInfo -- ^ List of packages to load into ghci
417402 -> (FilePath -> m ()) -- ^ Action to run with the path to generated temporary .ghci
418403 -> m ()
419−withGhciScript preCommands (toList -> packageInfos) f =
404+withGhciScript (toList -> packageInfos) f =
420405 withSystemTempDirectory "ob-ghci" $ \fp -> do
421406 let dotGhciPath = fp </> ".ghci"
422407 liftIO $ writeFile dotGhciPath dotGhci
@@ -428,8 +413,7 @@ withGhciScript preCommands (toList -> packageInfos) f =
428413 , [ "Backend" | "backend" `Set.member` packageNames ]
429414 , [ "Frontend" | "frontend" `Set.member` packageNames ]
430415 ]
431− dotGhci = unlines $
432− preCommands <>
416+ dotGhci = unlines
433417 [ if null modulesToLoad then "" else ":load " <> unwords modulesToLoad
434418 , "import qualified Obelisk.Run"
435419 , "import qualified Frontend"
@@ -482,7 +466,7 @@ runGhciRepl root (toList -> packages) ghciArgs =
482466 -- NOTE: We do *not* want to use $(staticWhich "ghci") here because we need the
483467 -- ghc that is provided by the shell in the user's project.
484468 nixShellWithoutPkgs root True False (packageInfoToNamePathMap packages) "ghc" $
485− Just $ unwords $ fmap bashEscape $ "ghci" : ghciArgs
469+ Just $ unwords $ "ghci" : ghciArgs -- TODO: Shell escape
486470
487471-- | Run ghcid
488472runGhcid
@@ -495,20 +479,24 @@ runGhcid
495479 -> m ()
496480runGhcid root chdirToRoot ghciArgs (toList -> packages) mcmd =
497481 nixShellWithoutPkgs root True chdirToRoot (packageInfoToNamePathMap packages) "ghc" $
498− Just $ unwords $ fmap bashEscape $ ghcidExePath : opts
482+ Just $ unwords $ ghcidExePath : opts -- TODO: Shell escape
499483 where
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− ]
484+ opts =
485+ [ "-W"
486+ , "--outputfile=ghcid-output.txt"
487+ ] <> map (\x -> "--reload='" <> x <> "'") reloadFiles
488+ <> map (\x -> "--restart='" <> x <> "'") restartFiles
489+ <> testCmd
490+ <> ["--command='" <> unwords ("ghci" : ghciArgs) <> "'"] -- TODO: Shell escape
491+ testCmd = maybeToList (flip fmap mcmd $ \cmd -> "--test='" <> cmd <> "'") -- TODO: Shell escape
492+
508493 adjustRoot x = if chdirToRoot then makeRelative root x else x
509494 reloadFiles = map adjustRoot [root </> "config"]
510495 restartFiles = map (adjustRoot . _cabalPackageInfo_packageFile) packages
511496
497+mkGhciScriptArg :: FilePath -> [String]
498+mkGhciScriptArg dotGhci = ["-ghci-script", dotGhci]
499+
512500getFreePort :: MonadIO m => m Socket.PortNumber
513501getFreePort = liftIO $ Socket.withSocketsDo $ do
514502 addr:_ <- Socket.getAddrInfo (Just Socket.defaultHints) (Just "127.0.0.1") (Just "0")