{-# LANGUAGE NoImplicitPrelude   #-}
{-# LANGUAGE OverloadedRecordDot #-}
{-# LANGUAGE OverloadedStrings   #-}

{-|
Module      : Stack.PackageFile
Description : All package-level file-gathering logic.
License     : BSD-3-Clause

A module which exports all package-level file-gathering logic.
-}

module Stack.PackageFile
  ( getPackageFile
  , stackPackageFileFromCabal
  ) where

import qualified Data.Map.Strict as M
import qualified Data.Set as S
import           Distribution.CabalSpecVersion ( CabalSpecVersion )
import qualified Distribution.PackageDescription as Cabal
import           Distribution.Simple.Glob ( matchDirFileGlob )
import           Distribution.Utils.Path ( getSymbolicPath )
import           Path ( parent, (</>) )
import           Path.Extra ( forgivingResolveFile, rejectMissingFile )
import           Path.IO ( doesFileExist )
import           Stack.ComponentFile
                   ( ComponentFile (..), resolveOrWarn, stackBenchmarkFiles
                   , stackExecutableFiles, stackLibraryFiles
                   , stackTestSuiteFiles
                   )
import           Stack.Constants
                   ( relFileHpackPackageConfig, relFileSetupHs, relFileSetupLhs
                   )
import           Stack.Constants.Config ( distDirFromDir )
import           Stack.Prelude
import           Stack.Types.BuildConfig ( HasBuildConfig (..) )
import           Stack.Types.CompilerPaths ( cabalVersionL )
import           Stack.Types.EnvConfig ( HasEnvConfig (..) )
import           Stack.Types.NamedComponent ( NamedComponent (..) )
import           Stack.Types.Package ( Package(..) )
import           Stack.Types.PackageFile
                   ( GetPackageFileContext (..), PackageComponentFile (..)
                   , StackPackageFile (..)
                   )
import qualified System.FilePath as FilePath
import           System.IO.Error ( isUserError )

-- | Resolve the file, if it can't be resolved, warn for the user

-- (purely to be helpful).

resolveFileOrWarn ::
     FilePath.FilePath
  -> RIO GetPackageFileContext (Maybe (Path Abs File))
resolveFileOrWarn :: FilePath -> RIO GetPackageFileContext (Maybe (Path Abs File))
resolveFileOrWarn = Text
-> (Path Abs Dir
    -> FilePath -> RIO GetPackageFileContext (Maybe (Path Abs File)))
-> FilePath
-> RIO GetPackageFileContext (Maybe (Path Abs File))
forall a.
Text
-> (Path Abs Dir
    -> FilePath -> RIO GetPackageFileContext (Maybe a))
-> FilePath
-> RIO GetPackageFileContext (Maybe a)
resolveOrWarn Text
"File" Path Abs Dir
-> FilePath -> RIO GetPackageFileContext (Maybe (Path Abs File))
forall {m :: * -> *}.
MonadIO m =>
Path Abs Dir -> FilePath -> m (Maybe (Path Abs File))
f
 where
  f :: Path Abs Dir -> FilePath -> m (Maybe (Path Abs File))
f Path Abs Dir
p FilePath
x = Path Abs Dir -> FilePath -> m (Maybe (Path Abs File))
forall {m :: * -> *}.
MonadIO m =>
Path Abs Dir -> FilePath -> m (Maybe (Path Abs File))
forgivingResolveFile Path Abs Dir
p FilePath
x m (Maybe (Path Abs File))
-> (Maybe (Path Abs File) -> m (Maybe (Path Abs File)))
-> m (Maybe (Path Abs File))
forall a b. m a -> (a -> m b) -> m b
forall (m :: * -> *) a b. Monad m => m a -> (a -> m b) -> m b
>>= Maybe (Path Abs File) -> m (Maybe (Path Abs File))
forall (m :: * -> *).
MonadIO m =>
Maybe (Path Abs File) -> m (Maybe (Path Abs File))
rejectMissingFile

-- | Get all files referenced by the package.

packageDescModulesAndFiles ::
     Package
  -> RIO
       GetPackageFileContext
       PackageComponentFile
packageDescModulesAndFiles :: Package -> RIO GetPackageFileContext PackageComponentFile
packageDescModulesAndFiles Package
pkg = do
  packageExtraFile <- CabalSpecVersion
-> StackPackageFile
-> RIO GetPackageFileContext (Set (Path Abs File))
resolveGlobFilesFromStackPackageFile
              Package
pkg.cabalSpec Package
pkg.file
  let initialValue = PackageComponentFile
forall a. Monoid a => a
mempty{packageExtraFile=packageExtraFile}
      accumulator ::
           Applicative f
        => (t -> f (NamedComponent, ComponentFile))
        -> t
        -> f PackageComponentFile
        -> f PackageComponentFile
      accumulator t -> f (NamedComponent, ComponentFile)
f t
comp f PackageComponentFile
st = (PackageComponentFile
-> (NamedComponent, ComponentFile) -> PackageComponentFile
insertComponentFile (PackageComponentFile
 -> (NamedComponent, ComponentFile) -> PackageComponentFile)
-> f PackageComponentFile
-> f ((NamedComponent, ComponentFile) -> PackageComponentFile)
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> f PackageComponentFile
st) f ((NamedComponent, ComponentFile) -> PackageComponentFile)
-> f (NamedComponent, ComponentFile) -> f PackageComponentFile
forall a b. f (a -> b) -> f a -> f b
forall (f :: * -> *) a b. Applicative f => f (a -> b) -> f a -> f b
<*> t -> f (NamedComponent, ComponentFile)
f t
comp
      gatherCompFileCollection ::
           (Applicative f, Foldable t)
        => (a -> f (NamedComponent, ComponentFile))
        -> (Package -> t a)
        -> f PackageComponentFile
        -> f PackageComponentFile
      gatherCompFileCollection a -> f (NamedComponent, ComponentFile)
createCompFileFn Package -> t a
getCompFn f PackageComponentFile
res =
        (a -> f PackageComponentFile -> f PackageComponentFile)
-> f PackageComponentFile -> t a -> f PackageComponentFile
forall a b. (a -> b -> b) -> b -> t a -> b
forall (t :: * -> *) a b.
Foldable t =>
(a -> b -> b) -> b -> t a -> b
foldr' ((a -> f (NamedComponent, ComponentFile))
-> a -> f PackageComponentFile -> f PackageComponentFile
forall (f :: * -> *) t.
Applicative f =>
(t -> f (NamedComponent, ComponentFile))
-> t -> f PackageComponentFile -> f PackageComponentFile
accumulator a -> f (NamedComponent, ComponentFile)
createCompFileFn) f PackageComponentFile
res (Package -> t a
getCompFn Package
pkg)
  gatherCompFileCollection stackLibraryFiles (.library)
    . gatherCompFileCollection stackLibraryFiles (.subLibraries)
    . gatherCompFileCollection stackExecutableFiles (.executables)
    . gatherCompFileCollection stackTestSuiteFiles (.testSuites)
    . gatherCompFileCollection stackBenchmarkFiles (.benchmarks)
    $ pure initialValue

resolveGlobFilesFromStackPackageFile ::
     CabalSpecVersion
  -> StackPackageFile
  -> RIO GetPackageFileContext (Set (Path Abs File))
resolveGlobFilesFromStackPackageFile :: CabalSpecVersion
-> StackPackageFile
-> RIO GetPackageFileContext (Set (Path Abs File))
resolveGlobFilesFromStackPackageFile
    CabalSpecVersion
csvV
    (StackPackageFile [FilePath]
extraSrcFilesV FilePath
dataDirV [FilePath]
dataFilesV)
  = CabalSpecVersion
-> [FilePath] -> RIO GetPackageFileContext (Set (Path Abs File))
resolveGlobFiles
      CabalSpecVersion
csvV
      ([FilePath]
extraSrcFilesV [FilePath] -> [FilePath] -> [FilePath]
forall a. [a] -> [a] -> [a]
++ (FilePath -> FilePath) -> [FilePath] -> [FilePath]
forall a b. (a -> b) -> [a] -> [b]
map (FilePath
dataDirV FilePath -> FilePath -> FilePath
FilePath.</>) [FilePath]
dataFilesV)

-- | Resolve globbing of files (e.g. data files) to absolute paths.

resolveGlobFiles ::
     CabalSpecVersion -- ^ Cabal file version

  -> [String]
  -> RIO GetPackageFileContext (Set (Path Abs File))
resolveGlobFiles :: CabalSpecVersion
-> [FilePath] -> RIO GetPackageFileContext (Set (Path Abs File))
resolveGlobFiles CabalSpecVersion
cabalFileVersion =
  ([[Maybe (Path Abs File)]] -> Set (Path Abs File))
-> RIO GetPackageFileContext [[Maybe (Path Abs File)]]
-> RIO GetPackageFileContext (Set (Path Abs File))
forall a b.
(a -> b)
-> RIO GetPackageFileContext a -> RIO GetPackageFileContext b
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
fmap ([Path Abs File] -> Set (Path Abs File)
forall a. Ord a => [a] -> Set a
S.fromList ([Path Abs File] -> Set (Path Abs File))
-> ([[Maybe (Path Abs File)]] -> [Path Abs File])
-> [[Maybe (Path Abs File)]]
-> Set (Path Abs File)
forall b c a. (b -> c) -> (a -> b) -> a -> c
. ([Maybe (Path Abs File)] -> [Path Abs File])
-> [[Maybe (Path Abs File)]] -> [Path Abs File]
forall (t :: * -> *) a b. Foldable t => (a -> [b]) -> t a -> [b]
concatMap [Maybe (Path Abs File)] -> [Path Abs File]
forall a. [Maybe a] -> [a]
catMaybes) (RIO GetPackageFileContext [[Maybe (Path Abs File)]]
 -> RIO GetPackageFileContext (Set (Path Abs File)))
-> ([FilePath]
    -> RIO GetPackageFileContext [[Maybe (Path Abs File)]])
-> [FilePath]
-> RIO GetPackageFileContext (Set (Path Abs File))
forall b c a. (b -> c) -> (a -> b) -> a -> c
. (FilePath -> RIO GetPackageFileContext [Maybe (Path Abs File)])
-> [FilePath]
-> RIO GetPackageFileContext [[Maybe (Path Abs File)]]
forall (t :: * -> *) (m :: * -> *) a b.
(Traversable t, Monad m) =>
(a -> m b) -> t a -> m (t b)
forall (m :: * -> *) a b. Monad m => (a -> m b) -> [a] -> m [b]
mapM FilePath -> RIO GetPackageFileContext [Maybe (Path Abs File)]
resolve
 where
  resolve :: FilePath -> RIO GetPackageFileContext [Maybe (Path Abs File)]
  resolve :: FilePath -> RIO GetPackageFileContext [Maybe (Path Abs File)]
resolve FilePath
name =
    if Char
'*' Char -> FilePath -> Bool
forall a. Eq a => a -> [a] -> Bool
forall (t :: * -> *) a. (Foldable t, Eq a) => a -> t a -> Bool
`elem` FilePath
name
      then FilePath -> RIO GetPackageFileContext [Maybe (Path Abs File)]
explode FilePath
name
      else (Maybe (Path Abs File) -> [Maybe (Path Abs File)])
-> RIO GetPackageFileContext (Maybe (Path Abs File))
-> RIO GetPackageFileContext [Maybe (Path Abs File)]
forall a b.
(a -> b)
-> RIO GetPackageFileContext a -> RIO GetPackageFileContext b
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
fmap Maybe (Path Abs File) -> [Maybe (Path Abs File)]
forall a. a -> [a]
forall (f :: * -> *) a. Applicative f => a -> f a
pure (FilePath -> RIO GetPackageFileContext (Maybe (Path Abs File))
resolveFileOrWarn FilePath
name)

  explode :: FilePath -> RIO GetPackageFileContext [Maybe (Path Abs File)]
  explode :: FilePath -> RIO GetPackageFileContext [Maybe (Path Abs File)]
explode FilePath
name = do
    dir <- (GetPackageFileContext -> Path Abs Dir)
-> RIO GetPackageFileContext (Path Abs Dir)
forall r (m :: * -> *) a. MonadReader r m => (r -> a) -> m a
asks (Path Abs File -> Path Abs Dir
forall b t. Path b t -> Path b Dir
parent (Path Abs File -> Path Abs Dir)
-> (GetPackageFileContext -> Path Abs File)
-> GetPackageFileContext
-> Path Abs Dir
forall b c a. (b -> c) -> (a -> b) -> a -> c
. (.file))
    names <- matchDirFileGlob' (toFilePath dir) name
    mapM resolveFileOrWarn names

  matchDirFileGlob' ::
       FilePath
    -> FilePath
    -> RIO GetPackageFileContext [FilePath]
  matchDirFileGlob' :: FilePath -> FilePath -> RIO GetPackageFileContext [FilePath]
matchDirFileGlob' FilePath
dir FilePath
glob =
    RIO GetPackageFileContext [FilePath]
-> (IOException -> RIO GetPackageFileContext [FilePath])
-> RIO GetPackageFileContext [FilePath]
forall (m :: * -> *) e a.
(MonadUnliftIO m, Exception e) =>
m a -> (e -> m a) -> m a
catch
      (IO [FilePath] -> RIO GetPackageFileContext [FilePath]
forall a. IO a -> RIO GetPackageFileContext a
forall (m :: * -> *) a. MonadIO m => IO a -> m a
liftIO (Verbosity
-> CabalSpecVersion -> FilePath -> FilePath -> IO [FilePath]
matchDirFileGlob Verbosity
forall a. Bounded a => a
minBound CabalSpecVersion
cabalFileVersion FilePath
dir FilePath
glob))
      ( \(IOException
e :: IOException) ->
        if IOException -> Bool
isUserError IOException
e
          then do
            [StyleDoc] -> RIO GetPackageFileContext ()
forall env (m :: * -> *).
(HasCallStack, HasTerm env, MonadReader env m, MonadIO m) =>
[StyleDoc] -> m ()
prettyWarnL
              [ FilePath -> StyleDoc
flow FilePath
"Wildcard does not match any files:"
              , Style -> StyleDoc -> StyleDoc
style Style
File (StyleDoc -> StyleDoc) -> StyleDoc -> StyleDoc
forall a b. (a -> b) -> a -> b
$ FilePath -> StyleDoc
forall a. IsString a => FilePath -> a
fromString FilePath
glob
              , StyleDoc
line StyleDoc -> StyleDoc -> StyleDoc
forall a. Semigroup a => a -> a -> a
<> FilePath -> StyleDoc
flow FilePath
"in directory:"
              , Style -> StyleDoc -> StyleDoc
style Style
Dir (StyleDoc -> StyleDoc) -> StyleDoc -> StyleDoc
forall a b. (a -> b) -> a -> b
$ FilePath -> StyleDoc
forall a. IsString a => FilePath -> a
fromString FilePath
dir
              ]
            [FilePath] -> RIO GetPackageFileContext [FilePath]
forall a. a -> RIO GetPackageFileContext a
forall (f :: * -> *) a. Applicative f => a -> f a
pure []
          else IOException -> RIO GetPackageFileContext [FilePath]
forall (m :: * -> *) e a. (MonadIO m, Exception e) => e -> m a
throwIO IOException
e
      )

-- | Gets all of the modules, files, build files, and data files that constitute

-- the package. This is primarily used for dirtiness checking during build, as

-- well as use by "stack ghci"

getPackageFile ::
     ( HasEnvConfig s, MonadReader s m, MonadThrow m, MonadUnliftIO m )
  => Package
  -> Path Abs File
  -> m PackageComponentFile
getPackageFile :: forall s (m :: * -> *).
(HasEnvConfig s, MonadReader s m, MonadThrow m, MonadUnliftIO m) =>
Package -> Path Abs File -> m PackageComponentFile
getPackageFile Package
pkg Path Abs File
cabalFP =
  StyleDoc -> m PackageComponentFile -> m PackageComponentFile
forall env (m :: * -> *) a.
(HasCallStack, HasTerm env, MonadReader env m, MonadIO m,
 MonadUnliftIO m) =>
StyleDoc -> m a -> m a
debugBracket (StyleDoc
"getPackageFiles" StyleDoc -> StyleDoc -> StyleDoc
<+> Path Abs File -> StyleDoc
forall a. Pretty a => a -> StyleDoc
pretty Path Abs File
cabalFP) (m PackageComponentFile -> m PackageComponentFile)
-> m PackageComponentFile -> m PackageComponentFile
forall a b. (a -> b) -> a -> b
$ do
    let pkgDir :: Path Abs Dir
pkgDir = Path Abs File -> Path Abs Dir
forall b t. Path b t -> Path b Dir
parent Path Abs File
cabalFP
    distDir <- Path Abs Dir -> m (Path Abs Dir)
forall env (m :: * -> *).
(HasEnvConfig env, MonadReader env m, MonadThrow m) =>
Path Abs Dir -> m (Path Abs Dir)
distDirFromDir Path Abs Dir
pkgDir
    bc <- view buildConfigL
    cabalVer <- view cabalVersionL
    packageComponentFile <-
      runRIO
        (GetPackageFileContext cabalFP distDir bc cabalVer)
        (packageDescModulesAndFiles pkg)
    setupFiles <-
      if pkg.buildType == Cabal.Custom
        then do
          let setupHsPath = Path Abs Dir
pkgDir Path Abs Dir -> Path Rel File -> Path Abs File
forall b t. Path b Dir -> Path Rel t -> Path b t
</> Path Rel File
relFileSetupHs
              setupLhsPath = Path Abs Dir
pkgDir Path Abs Dir -> Path Rel File -> Path Abs File
forall b t. Path b Dir -> Path Rel t -> Path b t
</> Path Rel File
relFileSetupLhs
          setupHsExists <- doesFileExist setupHsPath
          if setupHsExists
            then pure (S.singleton setupHsPath)
            else do
              setupLhsExists <- doesFileExist setupLhsPath
              if setupLhsExists
                then pure (S.singleton setupLhsPath)
                else pure S.empty
        else pure S.empty
    moreBuildFiles <- fmap (S.insert cabalFP . S.union setupFiles) $ do
      let hpackPath = Path Abs Dir
pkgDir Path Abs Dir -> Path Rel File -> Path Abs File
forall b t. Path b Dir -> Path Rel t -> Path b t
</> Path Rel File
relFileHpackPackageConfig
      hpackExists <- doesFileExist hpackPath
      pure $ if hpackExists then S.singleton hpackPath else S.empty
    pure packageComponentFile
      { packageExtraFile =
          moreBuildFiles <> packageComponentFile.packageExtraFile
      }

-- | For the given contents of a Cabal file, yields the information from it that

-- Stack needs to track files.

stackPackageFileFromCabal :: Cabal.PackageDescription -> StackPackageFile
stackPackageFileFromCabal :: PackageDescription -> StackPackageFile
stackPackageFileFromCabal PackageDescription
cabalPkg =
  [FilePath] -> FilePath -> [FilePath] -> StackPackageFile
StackPackageFile
    (PackageDescription -> [FilePath]
Cabal.extraSrcFiles PackageDescription
cabalPkg)
    (PackageDescription -> FilePath
Cabal.dataDir PackageDescription
cabalPkg)
    (PackageDescription -> [FilePath]
Cabal.dataFiles PackageDescription
cabalPkg)

insertComponentFile ::
     PackageComponentFile
  -> (NamedComponent, ComponentFile)
  -> PackageComponentFile
insertComponentFile :: PackageComponentFile
-> (NamedComponent, ComponentFile) -> PackageComponentFile
insertComponentFile PackageComponentFile
packageCompFile (NamedComponent
name, ComponentFile
compFile) =
  Map NamedComponent (Map ModuleName (Path Abs File))
-> Map NamedComponent [DotCabalPath]
-> Set (Path Abs File)
-> [PackageWarning]
-> PackageComponentFile
PackageComponentFile Map NamedComponent (Map ModuleName (Path Abs File))
nCompFile Map NamedComponent [DotCabalPath]
nDotCollec Set (Path Abs File)
packageExtraFile [PackageWarning]
nWarnings
 where
  (ComponentFile Map ModuleName (Path Abs File)
moduleFileMap [DotCabalPath]
dotCabalFileList [PackageWarning]
warningsCollec) = ComponentFile
compFile
  (PackageComponentFile Map NamedComponent (Map ModuleName (Path Abs File))
modules Map NamedComponent [DotCabalPath]
files Set (Path Abs File)
packageExtraFile [PackageWarning]
warnings) =
    PackageComponentFile
packageCompFile
  nCompFile :: Map NamedComponent (Map ModuleName (Path Abs File))
nCompFile = NamedComponent
-> Map ModuleName (Path Abs File)
-> Map NamedComponent (Map ModuleName (Path Abs File))
-> Map NamedComponent (Map ModuleName (Path Abs File))
forall k a. Ord k => k -> a -> Map k a -> Map k a
M.insert NamedComponent
name Map ModuleName (Path Abs File)
moduleFileMap Map NamedComponent (Map ModuleName (Path Abs File))
modules
  nDotCollec :: Map NamedComponent [DotCabalPath]
nDotCollec = NamedComponent
-> [DotCabalPath]
-> Map NamedComponent [DotCabalPath]
-> Map NamedComponent [DotCabalPath]
forall k a. Ord k => k -> a -> Map k a -> Map k a
M.insert NamedComponent
name [DotCabalPath]
dotCabalFileList Map NamedComponent [DotCabalPath]
files
  nWarnings :: [PackageWarning]
nWarnings = [PackageWarning]
warningsCollec [PackageWarning] -> [PackageWarning] -> [PackageWarning]
forall a. [a] -> [a] -> [a]
++ [PackageWarning]
warnings