packages feed

tavro-0.1.0.2: src/Tavro/LicenseList.hs

{-# LANGUAGE TemplateHaskell #-}

-- | the SPDX license list: ids and names from licenses.json and
-- exceptions.json, and a matcher per template. the copy in data/ is
-- compiled in, and a license-list-data checkout can stand in for it at run
-- time
module Tavro.LicenseList
  ( LicenseList (..),
    Entry (..),
    Kind (..),
    embedded,
    fromDirectory,
    fromParts,
  )
where

import Control.Applicative ((<|>))
import Control.Exception (IOException, try)
import Control.Monad (filterM, forM)
import Data.Aeson (FromJSON (..), eitherDecodeStrict, withObject, (.!=), (.:), (.:?))
import Data.ByteString (ByteString)
import Data.ByteString qualified as BS
import Data.FileEmbed (embedDir, embedFile)
import Data.List (isSuffixOf)
import Data.Map.Strict qualified as Map
import Data.Maybe (mapMaybe)
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.FilePath (takeFileName, (</>))
import Tavro.Match (Matcher, compileMatcher, matcherRequired)
import Tavro.Required (readRequiredKeys, requiredKeysIn)
import Tavro.Template (parseTemplate)
import Tavro.Text (decodeLenient, prepareTemplate)

data Kind = License | Exception
  deriving stock (Eq, Ord, Show)

data Entry = Entry
  { eId :: Text,
    eName :: Text,
    eKind :: Kind,
    eDeprecated :: Bool,
    eOsiApproved :: Bool,
    -- | lazy, so only the templates a run needs get compiled
    eMatcher :: Matcher,
    -- | the keys every match has to contain, worked out at build time for
    -- the embedded list so the prefilter doesn't compile anything
    eRequired :: [Text],
    -- | the standard license header, the notice that goes in source files,
    -- and its required keys
    eHeader :: Maybe ([Text], Matcher)
  }

data LicenseList = LicenseList
  { llVersion :: Text,
    llEntries :: [Entry]
  }

data Listed = Listed
  { lId :: Text,
    lName :: Text,
    lDeprecated :: Bool,
    lOsi :: Bool
  }

newtype Licenses = Licenses (Text, [Listed])

newtype Exceptions = Exceptions [Listed]

instance FromJSON Licenses where
  parseJSON = withObject "licenses.json" $ \o -> do
    version <- o .: "licenseListVersion"
    ls <- o .: "licenses" >>= mapM (withObject "license" listed)
    pure (Licenses (version, ls))
    where
      listed l =
        Listed
          <$> l .: "licenseId"
          <*> l .: "name"
          <*> l .:? "isDeprecatedLicenseId" .!= False
          <*> l .:? "isOsiApproved" .!= False

instance FromJSON Exceptions where
  parseJSON = withObject "exceptions.json" $ \o ->
    Exceptions <$> (o .: "exceptions" >>= mapM (withObject "exception" listed))
    where
      listed l =
        Listed
          <$> l .: "licenseExceptionId"
          <*> l .: "name"
          <*> l .:? "isDeprecatedLicenseId" .!= False
          <*> pure False

-- | licenses.json, exceptions.json, and the template and header template
-- files, by name
fromParts :: ByteString -> ByteString -> [(FilePath, ByteString)] -> [(FilePath, ByteString)] -> Map.Map FilePath [Text] -> Either String LicenseList
fromParts licensesJson exceptionsJson templates headers precomputed = do
  Licenses (version, ls) <- eitherDecodeStrict licensesJson
  Exceptions es <- eitherDecodeStrict exceptionsJson
  let lookupFor prefix files =
        let byFile = Map.fromList [(takeFileName f, (prefix </> takeFileName f, b)) | (f, b) <- files]
         in \l ->
              -- deprecated ids keep theirs under a prefix
              Map.lookup (T.unpack (lId l) <> ".template.txt") byFile
                <|> (if lDeprecated l then Map.lookup ("deprecated_" <> T.unpack (lId l) <> ".template.txt") byFile else Nothing)
      template = lookupFor "template" templates
      header = lookupFor "header" headers
      required (key, _) matcher = Map.findWithDefault (matcherRequired matcher) key precomputed
      entry kind l = do
        found@(_, bytes) <- template l
        let matcher = matcherOf bytes
        pure
          Entry
            { eId = lId l,
              eName = lName l,
              eKind = kind,
              eDeprecated = lDeprecated l,
              eOsiApproved = lOsi l,
              eMatcher = matcher,
              eRequired = required found matcher,
              eHeader = (\h@(_, hb) -> let hm = matcherOf hb in (required h hm, hm)) <$> header l
            }
  pure
    LicenseList
      { llVersion = version,
        llEntries = mapMaybe (entry License) ls <> mapMaybe (entry Exception) es
      }
  where
    matcherOf = compileMatcher . parseTemplate . prepareTemplate . decodeLenient

embedded :: LicenseList
embedded =
  either (error . ("the embedded license list is broken: " <>)) id $
    fromParts
      $(embedFile "data/licenses.json")
      $(embedFile "data/exceptions.json")
      $(embedDir "data/template")
      $(embedDir "data/header")
      ( Map.fromList
          ( [("template" </> f, ks) | (f, ks) <- readRequiredKeys $(requiredKeysIn "data/template")]
              <> [("header" </> f, ks) | (f, ks) <- readRequiredKeys $(requiredKeysIn "data/header")]
          )
      )

-- | a license-list-data checkout or release, or a directory laid out like
-- this package's data/
fromDirectory :: FilePath -> IO (Either String LicenseList)
fromDirectory dir = either (\(e :: IOException) -> Left (show e)) id <$> try load
  where
    load = do
      jsonDir <- filterM (\d -> doesFileExist (d </> "licenses.json")) [dir </> "json", dir]
      hasTemplates <- doesDirectoryExist (dir </> "template")
      case jsonDir of
        j : _ | hasTemplates -> do
          lic <- BS.readFile (j </> "licenses.json")
          exc <- BS.readFile (j </> "exceptions.json")
          templates <- readTemplates (dir </> "template")
          hasHeaders <- doesDirectoryExist (dir </> "header")
          headers <-
            if hasHeaders
              then readTemplates (dir </> "header")
              else headersFromDetails (j </> "details")
          pure $
            if null templates
              then Left (dir </> "template" <> " has no .template.txt files")
              else fromParts lic exc templates headers Map.empty
        _ -> pure (Left (dir <> " has no licenses.json and template/ directory"))
    readTemplates d = do
      names <- filter (".template.txt" `isSuffixOf`) <$> listDirectory d
      mapM (\n -> (,) n <$> BS.readFile (d </> n)) names

newtype Details = Details (Text, Bool, Maybe Text)

instance FromJSON Details where
  parseJSON = withObject "license details" $ \o -> do
    lid <- o .: "licenseId"
    deprecated <- o .:? "isDeprecatedLicenseId" .!= False
    header <- o .:? "standardLicenseHeaderTemplate"
    pure (Details (lid, deprecated, header))

-- | license-list-data keeps header templates inside json/details, which is
-- what scripts/fetch-license-data.sh unpacks into data/header
headersFromDetails :: FilePath -> IO [(FilePath, ByteString)]
headersFromDetails d = do
  exists <- doesDirectoryExist d
  names <- if exists then filter (".json" `isSuffixOf`) <$> listDirectory d else pure []
  fmap concat . forM names $ \n -> do
    bytes <- BS.readFile (d </> n)
    pure $ case eitherDecodeStrict bytes of
      Right (Details (lid, deprecated, Just h))
        | not (T.null (T.strip h)) ->
            [((if deprecated then "deprecated_" else "") <> T.unpack lid <> ".template.txt", TE.encodeUtf8 h)]
      _ -> []