packages feed

tavro-0.1.0.2: src/Tavro/Stack.hs

-- | the packages a stack project links in, for the same license listing
-- --cabal does from cabal's build plan.
--
-- stack has no plan file, but @stack ls dependencies json@ gives the
-- project's packages and the graph under them. that graph is too wide for
-- this, though: for a package from the snapshot it lists what every
-- component needs, so vector's test suite brings in tasty. the package
-- databases are exact, since a registered library lists only what it
-- links against, so installed packages are followed through those, and
-- stack's graph only fills in for what isn't built yet.
--
-- stack's license field is no use either: it turns SPDX back into Cabal's
-- old names, and a compound license into something like
-- GPL30orlaterANDCCBY30. licenses come from the package databases and the
-- Hackage index, like for cabal
module Tavro.Stack
  ( StackDep (..),
    parseDependencies,
    stackDependencies,
    stackPackages,
    stackToolchain,
  )
where

import Control.Exception (IOException, try)
import Control.Monad (filterM, forM)
import Data.Aeson (FromJSON (..), eitherDecodeStrict, withObject, (.!=), (.:), (.:?))
import Data.ByteString qualified as BS
import Data.Containers.ListUtils (nubOrd)
import Data.Map.Strict qualified as Map
import Data.Maybe (isNothing, listToMaybe, mapMaybe)
import Data.Set qualified as Set
import Data.Text (Text)
import Data.Text qualified as T
import Data.Text.Encoding qualified as TE
import System.Directory (doesDirectoryExist, doesFileExist, listDirectory)
import System.Exit (ExitCode (..))
import System.FilePath (takeDirectory, takeExtension, (</>))
import System.Process (CreateProcess (..), proc, readCreateProcessWithExitCode)
import Tavro.Cabal

-- | one entry of @stack ls dependencies json@
data StackDep = StackDep
  { sdName :: Text,
    sdVersion :: Text,
    sdDependencies :: [Text],
    sdProjectDir :: Maybe FilePath
  }
  deriving stock (Eq, Show)

instance FromJSON StackDep where
  parseJSON = withObject "stack dependency" $ \o -> do
    sdName <- o .: "name"
    sdVersion <- o .: "version"
    sdDependencies <- o .:? "dependencies" .!= []
    location <- o .:? "location"
    sdProjectDir <- case location of
      Nothing -> pure Nothing
      Just l -> flip (withObject "location") l $ \lo -> do
        kind <- lo .:? "type"
        url <- lo .:? "url"
        pure $
          if kind == Just ("project package" :: Text)
            then T.unpack <$> (url >>= T.stripPrefix "file://")
            else Nothing
    pure StackDep {..}

parseDependencies :: BS.ByteString -> Either String [StackDep]
parseDependencies = eitherDecodeStrict

-- | @stack ls dependencies json@ for the project in a directory. with
-- tests, the project's test suites count too, like --test does for stack
stackDependencies :: FilePath -> [String] -> Bool -> IO (Either String [StackDep])
stackDependencies dir stackArgs tests = do
  out <- stack dir stackArgs (["ls", "dependencies", "json"] <> ["--test" | tests])
  pure (out >>= parseDependencies . TE.encodeUtf8)

data Installed = Installed
  { iId :: Text,
    iName :: Text,
    iVersion :: Text,
    iSublibrary :: Maybe Text,
    iDepends :: [Text]
  }

-- | the packages linked into the project's packages: the project packages
-- and what their libraries, executables, and (with stack's --test) test
-- suites need, then down through each library's own dependencies
stackPackages :: [FilePath] -> [StackDep] -> IO [Package]
stackPackages dbs deps = do
  installed <- concat <$> mapM readDb dbs
  let byId = Map.fromList [(iId i, i) | i <- installed]
      -- a package by name and version means its main library. sublibraries
      -- are only reached by id, from what depends on them: vector's
      -- benchmarks-O2 sublibrary needs tasty, but nothing links that
      mainLib = Map.fromList [((iName i, iVersion i), i) | i <- installed, isNothing (iSublibrary i)]
      versions = Map.fromList [(sdName d, sdVersion d) | d <- deps]
      stackDeps = Map.fromList [(sdName d, sdDependencies d) | d <- deps]
      projects = [d | d <- deps, Just _ <- [sdProjectDir d]]
      byName n = (n, Map.findWithDefault "" n versions)
      -- installed libraries are followed by id through their package db
      -- entries, anything else by name through stack's graph
      node k = maybe (Right k) Left (Map.lookup k mainLib)
      next = \case
        Left i -> [maybe (Right ("", "")) Left (Map.lookup dep byId) | dep <- iDepends i]
        Right (n, _) -> map (node . byName) (Map.findWithDefault [] n stackDeps)
      nameOf = \case
        Left i -> (iName i, iVersion i)
        Right k -> k
      keyOf = \case
        Left i -> Left (iId i)
        Right k -> Right k
      walk seen acc = \case
        [] -> acc
        x : rest
          | keyOf x `Set.member` seen -> walk seen acc rest
          | otherwise -> walk (Set.insert (keyOf x) seen) (Map.insertWith (<>) (nameOf x) (either (pure . iId) (const []) x) acc) (next x <> rest)
      -- a project package's own dependencies come from stack, which knows
      -- which components are being built
      reached =
        Map.delete ("", "") $
          walk Set.empty Map.empty (concatMap (map (node . byName) . sdDependencies) projects)
      projectDirs = Map.fromList [((sdName d, sdVersion d), dir) | d <- projects, Just dir <- [sdProjectDir d]]
  pure
    [ Package
        { pName = n,
          pVersion = v,
          pInProject = Map.member (n, v) projectDirs,
          pIds = nubOrd (Map.findWithDefault [] (n, v) reached),
          pSrcPath = Map.lookup (n, v) projectDirs
        }
    | (n, v) <- Set.toList (Map.keysSet reached <> Map.keysSet projectDirs)
    ]

-- | the libraries registered in a package db. an internal library is
-- registered under a munged name, with the package's real one in
-- package-name
readDb :: FilePath -> IO [Installed]
readDb db = do
  exists <- doesDirectoryExist db
  names <- if exists then filter ((== ".conf") . takeExtension) <$> listDirectory db else pure []
  fmap catMaybes' . forM names $ \n -> do
    fields <- confFields (db </> n)
    pure $ do
      i <- lookup "id" fields
      name <- lookup "package-name" fields `orElse` lookup "name" fields
      version <- lookup "version" fields
      pure
        Installed
          { iId = i,
            iName = name,
            iVersion = version,
            iSublibrary = lookup "lib-name" fields,
            iDepends = maybe [] T.words (lookup "depends" fields)
          }
  where
    orElse a b = maybe b Just a
    catMaybes' = mapMaybe id

-- | the package dbs and docs for a stack project, from @stack path@, and
-- the Hackage index stack's pantry keeps
stackToolchain :: FilePath -> [String] -> IO (Either String Toolchain)
stackToolchain dir stackArgs = do
  out <- stack dir stackArgs ["path", "--global-pkg-db", "--snapshot-pkg-db", "--local-pkg-db", "--stack-root", "--compiler-exe"]
  case out of
    Left err -> pure (Left err)
    Right text -> do
      let paths = Map.fromList [(T.strip k, T.unpack (T.strip (T.drop 1 v))) | l <- T.lines text, let (k, v) = T.breakOn ":" l, not (T.null v)]
          path k = Map.lookup k paths
          dbs = mapMaybe path ["local-pkg-db", "snapshot-pkg-db", "global-pkg-db"]
      existing <- filterM doesDirectoryExist dbs
      index <- case path "stack-root" of
        Just root -> listToMaybe <$> filterM doesFileExist [root </> "pantry" </> "hackage" </> "01-index.tar"]
        Nothing -> pure Nothing
      -- ghc's docs, for the boot packages' license files, are next to its
      -- global db: <prefix>/lib/.../package.conf.d and <prefix>/share/doc
      docs <- case path "global-pkg-db" of
        Just g -> ghcDocDirsNear (takeDirectory g)
        Nothing -> pure []
      pure (Right Toolchain {tDbs = existing, tGhcDocs = docs, tIndex = index})

stack :: FilePath -> [String] -> [String] -> IO (Either String Text)
stack dir stackArgs args = do
  r <- try (readCreateProcessWithExitCode (proc "stack" (stackArgs <> args)) {cwd = Just dir} "")
  pure $ case r of
    Left (e :: IOException) -> Left ("can't run stack: " <> show e)
    Right (ExitSuccess, out, _) -> Right (T.pack out)
    Right (_, _, err) -> Left ("stack " <> unwords (stackArgs <> args) <> " failed:\n" <> err)