tavro-0.1.0.2: src/Tavro/Cabal.hs
-- | the licenses of the Hackage packages a cabal project links into its
-- executables, like Terra's %cargo_license_online macros do for crates.
--
-- cargo asks cargo tree. here the build plan cabal writes to
-- dist-newstyle/cache/plan.json says which units the project's components
-- depend on, and the installed package databases (the cabal store, and
-- ghc's own for the boot packages) say what each one declares in its
-- license field and where its license files went.
--
-- the declared license is what's reported, as with cargo. the license
-- files are read too: when one says something else, that's worth a
-- warning, and when the declared license isn't usable SPDX (OtherLicense,
-- a LicenseRef), the text is what's left to go on
module Tavro.Cabal
( Unit (..),
Plan (..),
readPlan,
linkedUnits,
Package (..),
packagesOf,
Toolchain (..),
findToolchain,
gatherLicenses,
PackageLicense (..),
Verdict (..),
judge,
isLicenseFile,
licenseFilesIn,
confFields,
ghcDocDirsNear,
)
where
import Control.Exception (IOException, try)
import Control.Monad (filterM, forM, mfilter)
import Data.Aeson (FromJSON (..), Value, eitherDecodeStrict, withObject, (.!=), (.:), (.:?))
import Data.ByteString qualified as BS
import Data.ByteString.Lazy qualified as LBS
import Data.Char (isSpace, toLower)
import Data.Containers.ListUtils (nubOrd)
import Data.List (intersect, isInfixOf, isPrefixOf, sort, sortOn)
import Data.Map.Strict qualified as Map
import Data.Maybe (catMaybes, fromMaybe, listToMaybe, mapMaybe)
import Data.Set qualified as Set
import Data.Text (Text)
import Data.Text qualified as T
import System.Directory (doesDirectoryExist, doesFileExist, getHomeDirectory, listDirectory, makeAbsolute)
import System.Environment (lookupEnv)
import System.Exit (ExitCode (..))
import System.FilePath (takeDirectory, takeExtension, takeFileName, (</>))
import System.Process (readProcessWithExitCode)
import Tavro.Spdx (Declared (..), FromText (..), Ids, describeGroups, expressionIds, fromFiles, readDeclared)
import Tavro.Text (decodeLenient)
-- | one unit of the install plan: a component of a package, or a whole
-- package when cabal builds it in one go (build-type Custom)
data Unit = Unit
{ uId :: Text,
uName :: Text,
uVersion :: Text,
uInProject :: Bool,
-- | "exe:tavro", "lib", ..., or Nothing for a whole package
uComponent :: Maybe Text,
-- | library dependencies. exe-depends are build tools, which aren't
-- linked in
uDepends :: [Text],
-- | for a whole package, each component's library dependencies
uComponents :: [(Text, [Text])],
uSrcPath :: Maybe FilePath
}
deriving stock (Eq, Show)
instance FromJSON Unit where
parseJSON = withObject "plan unit" $ \o -> do
uId <- o .: "id"
uName <- o .: "pkg-name"
uVersion <- o .: "pkg-version"
style <- o .:? "style"
uComponent <- o .:? "component-name"
uDepends <- o .:? "depends" .!= []
comps <- o .:? "components" .!= (Map.empty :: Map.Map Text Value)
uComponents <- forM (Map.toList comps) $ \(name, v) ->
(,) name <$> withObject "component" (\c -> c .:? "depends" .!= []) v
src <- o .:? "pkg-src"
uSrcPath <- maybe (pure Nothing) (withObject "pkg-src" (.:? "path")) src
pure Unit {uInProject = style == Just ("local" :: Text), ..}
data Plan = Plan
{ planCompiler :: Text,
planUnits :: [Unit]
}
instance FromJSON Plan where
parseJSON = withObject "plan.json" $ \o ->
Plan <$> o .: "compiler-id" <*> o .: "install-plan"
readPlan :: FilePath -> IO (Either String Plan)
readPlan path = do
r <- try (BS.readFile path)
pure $ case r of
Left (e :: IOException) -> Left (show e <> "\nrun cabal build (or cabal build --dry-run) first, which writes it")
Right bytes -> either (\e -> Left (path <> ": " <> e)) Right (eitherDecodeStrict bytes)
-- | the units linked into the chosen components of the project's own
-- packages, those components included. with none chosen, that's every
-- executable, or every library when there aren't any. only library
-- dependencies count: build tools and setup scripts aren't linked in, like
-- cargo's --edges no-build. test suites and benchmarks aren't chosen by
-- default, like --edges no-dev
linkedUnits :: [Text] -> Plan -> Either String [Unit]
linkedUnits wanted plan
| not (null missing) =
Left
( "no component "
<> T.unpack (T.intercalate ", " missing)
<> " in the plan. it has "
<> T.unpack (T.intercalate ", " available)
)
| null roots = Left "the plan has no executables or libraries of the project's own to look at"
| otherwise = Right (walk Set.empty (concatMap rootDeps roots) (map fst roots))
where
units = planUnits plan
byId = Map.fromList [(uId u, u) | u <- units]
local = filter uInProject units
-- (component name, the unit it's in)
components =
[(c, u) | u <- local, Just c <- [uComponent u]]
<> [(c, u) | u <- local, Nothing <- [uComponent u], (c, _) <- uComponents u]
available = nubOrd (map fst components)
isLib c = c == "lib" || "lib:" `T.isPrefixOf` c
chosen
| not (null wanted) = wanted
| any (("exe:" `T.isPrefixOf`) . fst) components = filter ("exe:" `T.isPrefixOf`) available
| otherwise = filter isLib available
missing = filter (`notElem` available) wanted
roots = [(u, c) | (c, u) <- components, c `elem` chosen]
rootDeps (u, c) = case uComponent u of
Just _ -> uDepends u
Nothing -> fromMaybe [] (lookup c (uComponents u))
-- a dependency on a whole package is a dependency on its libraries.
-- pre-existing units, ghc's boot packages, list theirs directly
depsOf u = case (uComponent u, uComponents u) of
(Nothing, cs@(_ : _)) -> concat [ds | (c, ds) <- cs, isLib c]
_ -> uDepends u
walk seen todo acc = case todo of
[] -> nubOrd' acc
i : rest
| i `Set.member` seen -> walk seen rest acc
| otherwise -> case Map.lookup i byId of
Nothing -> walk (Set.insert i seen) rest acc
Just u -> walk (Set.insert i seen) (depsOf u <> rest) (u : acc)
nubOrd' = Map.elems . Map.fromList . map (\u -> (uId u, u))
data Package = Package
{ pName :: Text,
pVersion :: Text,
pInProject :: Bool,
pIds :: [Text],
pSrcPath :: Maybe FilePath
}
deriving stock (Eq, Show)
packagesOf :: [Unit] -> [Package]
packagesOf us =
[ Package
{ pName = n,
pVersion = v,
pInProject = any uInProject group,
pIds = nubOrd (map uId group),
pSrcPath = listToMaybe (mapMaybe uSrcPath group)
}
| ((n, v), group) <- Map.toList (Map.fromListWith (flip (<>)) [((uName u, uVersion u), [u]) | u <- us])
]
-- | where installed packages are described: the store's package db and
-- ghc's own, store first
data Toolchain = Toolchain
{ tDbs :: [FilePath],
-- | ghc's docs, for the boot packages' license files
tGhcDocs :: [FilePath],
-- | Hackage's index of .cabal files, for packages the plan has that
-- aren't built yet
tIndex :: Maybe FilePath
}
-- | find the package dbs for the plan's compiler: the store from
-- @cabal path@ or the usual places, and ghc's global db from
-- @ghc --print-libdir@. extra dbs come first
findToolchain :: [FilePath] -> Plan -> IO Toolchain
findToolchain extraDbs plan = do
stores <- storeDirs
let compiler = T.unpack (planCompiler plan)
storeDbs <- nubOrd . concat <$> mapM (compilerDbs compiler) stores
libdir <- ghcLibdir compiler
globalDb <- maybe (pure []) (\l -> filterM doesDirectoryExist [l </> "package.conf.d"]) libdir
docs <- maybe (pure []) ghcDocDirsNear libdir
index <- listToMaybe <$> (indexCandidates >>= filterM doesFileExist)
pure Toolchain {tDbs = extraDbs <> storeDbs <> globalDb, tGhcDocs = docs, tIndex = index}
where
compilerDbs compiler store = do
listed <- try (listDirectory store)
let names = case listed of
Left (_ :: IOException) -> []
Right ns -> ns
forCompiler = sortOn (== compiler) [n | n <- names, n == compiler || (compiler <> "-") `isPrefixOf` n]
filterM doesDirectoryExist [store </> n </> "package.db" | n <- forCompiler]
indexCandidates = do
fromCabal <- run "cabal" ["path", "--remote-repo-cache"]
cabalDir <- lookupEnv "CABAL_DIR"
home <- getHomeDirectory
cache <- lookupEnv "XDG_CACHE_HOME"
let repo d = d </> "hackage.haskell.org" </> "01-index.tar"
pure
$ map repo
$ catMaybes [T.unpack . T.strip <$> fromCabal, (</> "packages") <$> cabalDir]
<> [home </> ".cabal" </> "packages", fromMaybe (home </> ".cache") cache </> "cabal" </> "packages"]
storeDirs = do
fromCabal <- run "cabal" ["path", "--store-dir"]
cabalDir <- lookupEnv "CABAL_DIR"
home <- getHomeDirectory
state <- lookupEnv "XDG_STATE_HOME"
pure $
catMaybes [T.unpack . T.strip <$> fromCabal, (</> "store") <$> cabalDir]
<> [home </> ".cabal" </> "store", fromMaybe (home </> ".local" </> "state") state </> "cabal" </> "store"]
-- ghc-9.10.3 if it's there, since plain ghc may be another version
ghcLibdir compiler = do
let version = drop 4 compiler
named <- run compiler ["--print-libdir"]
case named of
Just l -> pure (Just (T.unpack (T.strip l)))
Nothing -> do
v <- run "ghc" ["--numeric-version"]
if fmap T.strip v == Just (T.pack version)
then fmap (T.unpack . T.strip) <$> run "ghc" ["--print-libdir"]
else pure Nothing
-- | where ghc keeps its boot packages' docs, license files included, given
-- its libdir. ghcup and bindists have share/doc/<platform>-ghc-<version>
-- a few levels up
ghcDocDirsNear :: FilePath -> IO [FilePath]
ghcDocDirsNear libdir = do
let ancestors = take 5 (iterate takeDirectory libdir)
shares <- filterM doesDirectoryExist [a </> "share" </> "doc" | a <- ancestors]
fmap concat . forM shares $ \share -> do
subs <- listDirectory share
pure (share : [share </> s | s <- subs, "-ghc-" `isInfixOf` s])
run :: FilePath -> [String] -> IO (Maybe Text)
run cmd args = do
r <- try (readProcessWithExitCode cmd args "")
pure $ case r of
Right (ExitSuccess, out, _) -> Just (T.pack out)
Right _ -> Nothing
Left (_ :: IOException) -> Nothing
data PackageLicense = PackageLicense
{ plPackage :: Package,
plDeclared :: Maybe Text,
plFiles :: [FilePath]
}
gatherLicenses :: Toolchain -> [Package] -> IO [PackageLicense]
gatherLicenses tc ps = do
found <- mapM installed ps
-- whatever isn't built yet is looked up in the index, in one pass
let unbuilt = [p | (p, Nothing) <- zip ps found, not (pInProject p)]
fromIndex <- case tIndex tc of
Just index | not (null unbuilt) -> indexLicenses index (Set.fromList [(pName p, pVersion p) | p <- unbuilt])
_ -> pure Map.empty
forM (zip ps found) $ \case
(_, Just pl) -> pure pl
(p, Nothing)
| pInProject p -> localLicense p
| otherwise -> pure (PackageLicense p (Map.lookup (pName p, pVersion p) fromIndex) [])
where
installed p
| pInProject p = pure Nothing
| otherwise = do
confs <- filterM doesFileExist [db </> T.unpack i <> ".conf" | i <- pIds p, db <- tDbs tc]
case confs of
[] -> pure Nothing
conf : _ -> do
fields <- confFields conf
let pkgroot = takeDirectory (takeDirectory conf)
resolve = T.unpack . T.replace "${pkgroot}" (T.pack pkgroot) . T.dropAround (== '"')
haddock = resolve <$> lookup "haddock-html" fields
-- the store keeps a package's docs, license files
-- included, in <store>/<id>/share/doc
storeDocs = [pkgroot </> T.unpack i </> "share" </> "doc" | i <- pIds p]
boot = [d </> T.unpack (pName p <> "-" <> pVersion p) | d <- tGhcDocs tc]
fedora = ["/usr/share/licenses/ghc-" <> T.unpack (pName p)]
-- stack puts license files in the haddock directory itself,
-- the cabal store one level up
files <- licenseFilesIn (maybe [] (\h -> [h, takeDirectory h]) haddock <> storeDocs <> boot <> fedora)
pure (Just (PackageLicense p (lookup "license" fields) files))
-- | the license fields of some packages' .cabal files, from Hackage's
-- 01-index.tar. it's a plain tar of <name>/<version>/<name>.cabal entries,
-- with a revised .cabal file added again later, so the last one wins
indexLicenses :: FilePath -> Set.Set (Text, Text) -> IO (Map.Map (Text, Text) Text)
indexLicenses index wanted = do
r <- try (LBS.readFile index)
pure $ case r of
Left (_ :: IOException) -> Map.empty
Right bytes -> go bytes Map.empty
where
go bytes acc
| LBS.length header < 512 || LBS.all (== 0) header = acc
| otherwise =
let name = field 0 100
prefix = field 345 155
path = if T.null prefix then name else prefix <> "/" <> name
size = octal (LBS.take 12 (LBS.drop 124 header))
padded = (size + 511) `div` 512 * 512
body = LBS.take size (LBS.drop 512 bytes)
acc' = case T.splitOn "/" path of
[n, v, file]
| file == n <> ".cabal",
(n, v) `Set.member` wanted,
Just l <- licenseField (decodeLenient (LBS.toStrict body)) ->
Map.insert (n, v) l acc
_ -> acc
in go (LBS.drop (512 + padded) bytes) acc'
where
header = LBS.take 512 bytes
field off len = decodeLenient (LBS.toStrict (LBS.takeWhile (/= 0) (LBS.take len (LBS.drop off header))))
octal = LBS.foldl' (\n c -> if c >= 48 && c <= 55 then n * 8 + fromIntegral (c - 48) else n) 0
-- | a package of the project: its .cabal file's license field, and the
-- license files at its top
localLicense :: Package -> IO PackageLicense
localLicense p = do
dir <- maybe (pure ".") makeAbsolute (pSrcPath p)
names <- sort <$> listDirectory dir
declared <- case [n | n <- names, takeExtension n == ".cabal"] of
cabal : _ -> licenseField <$> readText (dir </> cabal)
[] -> pure Nothing
files <- licenseFilesIn [dir]
pure (PackageLicense p declared files)
licenseField :: Text -> Maybe Text
licenseField t =
listToMaybe
[ T.strip (T.drop 1 v)
| l <- T.lines t,
not (startsWithSpace l),
let (k, v) = T.breakOn ":" l,
T.toLower (T.strip k) == "license",
not (T.null v)
]
-- | license files right in each directory, not below it
licenseFilesIn :: [FilePath] -> IO [FilePath]
licenseFilesIn dirs = fmap (nubOrd . concat) . forM dirs $ \d -> do
exists <- doesDirectoryExist d
if not exists
then pure []
else do
names <- sort . filter isLicenseFile <$> listDirectory d
filterM doesFileExist (map (d </>) names)
-- | LICENSE, LICENSE-MIT, COPYING.LIB, MIT-LICENSE.txt and so on
isLicenseFile :: FilePath -> Bool
isLicenseFile f =
let n = map toLower (takeFileName f)
in "licen" `isInfixOf` n || any (`isPrefixOf` n) ["copying", "copyright", "unlicense"]
-- | a package db entry's fields. a value can go on over indented lines
confFields :: FilePath -> IO [(Text, Text)]
confFields path = parse . T.lines <$> readText path
where
parse = \case
[] -> []
l : rest
| Just (k, v) <- field l ->
let (more, rest') = span (\x -> T.null x || startsWithSpace x) rest
in (k, T.strip (T.unwords (v : map T.strip more))) : parse rest'
| otherwise -> parse rest
field l
| T.null l || startsWithSpace l = Nothing
| otherwise = case T.breakOn ":" l of
(k, v) | not (T.null v) -> Just (T.strip k, T.drop 1 v)
_ -> Nothing
startsWithSpace :: Text -> Bool
startsWithSpace = maybe False (isSpace . fst) . T.uncons
readText :: FilePath -> IO Text
readText path = decodeLenient <$> BS.readFile path
data Verdict = Verdict
{ vPackage :: Package,
vExpression :: Text,
-- | things a packager should look at
vNotes :: [Text]
}
-- | decide a package's license from what it declares and what its license
-- files were identified as (each file's groups of ids that matched the
-- same text, more than one when the text can't tell them apart, like
-- GPL-2.0-only and GPL-2.0-or-later)
judge :: Ids -> PackageLicense -> [(FilePath, [[Text]])] -> Verdict
judge ids PackageLicense {..} identified = case declared of
Just (Spdx expr)
| not (null textIds) && null (expressionIds expr `intersect` textIds) ->
verdict expr ["declares " <> expr <> ", but " <> files <> " " <> describeGroups groups]
| otherwise -> verdict expr []
_ -> case fromFiles ids identified of
NoText -> verdict fallback [declaredNote <> ", and no license file says otherwise"]
Reads pieces -> verdict (T.intercalate " AND " pieces) [declaredNote <> ", so this is from " <> files]
Unclear why -> verdict fallback [declaredNote <> ", and " <> files <> " " <> why]
where
verdict expr notes = Verdict plPackage expr notes
stated = mfilter (not . T.null) (T.strip <$> plDeclared)
declared = readDeclared ids <$> stated
fallback = case declared of
Just (NotSpdx e) -> e
_ -> "NOASSERTION"
declaredNote = maybe "declares no license" (\d -> "declares " <> d <> ", which isn't an SPDX license") stated
groups = nubOrd (concatMap snd identified)
textIds = concat groups
files = T.intercalate ", " (map (T.pack . takeFileName . fst) identified)