packages feed

tavro-0.1.0.2: src/Tavro/Spdx.hs

module Tavro.Spdx
  ( Ids (..),
    idsFromEntries,
    Declared (..),
    readDeclared,
    legacyLicense,
    expressionIds,
    FromText (..),
    fromFiles,
    describeGroups,
    hasNoLicense,
  )
where

import Data.Char (isAlphaNum, isAscii, toUpper)
import Data.Containers.ListUtils (nubOrd)
import Data.List (partition, sort)
import Data.Maybe (fromMaybe)
import Data.Set (Set)
import Data.Set qualified as Set
import Data.Text (Text)
import Data.Text qualified as T
import Tavro.LicenseList (Entry (..), Kind (..))

data Ids = Ids
  { licenseIds :: Set Text,
    exceptionIds :: Set Text,
    deprecatedIds :: Set Text
  }

idsFromEntries :: [Entry] -> Ids
idsFromEntries es =
  Ids
    { licenseIds = current License,
      exceptionIds = current Exception,
      deprecatedIds = Set.fromList [eId e | e <- es, eDeprecated e]
    }
  where
    current kind = Set.fromList [eId e | e <- es, eKind e == kind, not (eDeprecated e)]

data Declared
  = Spdx Text
  | NotSpdx Text
  deriving stock (Eq, Show)

readDeclared :: Ids -> Text -> Declared
readDeclared ids raw =
  let stripped = T.strip raw
      converted = map (currentToken ids) (tokens (fromMaybe stripped (legacyLicense stripped)))
      expression = untokens (map snd converted)
   in if all fst converted then Spdx expression else NotSpdx expression

legacyLicense :: Text -> Maybe Text
legacyLicense = \case
  "BSD2" -> Just "BSD-2-Clause"
  "BSD3" -> Just "BSD-3-Clause"
  "BSD4" -> Just "BSD-4-Clause"
  "GPL-2" -> Just "GPL-2.0-only"
  "GPL-3" -> Just "GPL-3.0-only"
  "LGPL-2.1" -> Just "LGPL-2.1-only"
  "LGPL-3" -> Just "LGPL-3.0-only"
  "AGPL-3" -> Just "AGPL-3.0-only"
  "AllRightsReserved" -> Just "NONE"
  "UnspecifiedLicense" -> Just "NONE"
  _ -> Nothing

currentToken :: Ids -> Text -> (Bool, Text)
currentToken Ids {..} tok
  | tok `elem` ["(", ")"] = (True, tok)
  | upper `elem` ["AND", "OR", "WITH"] = (True, upper)
  | tok `elem` ["NONE", "NOASSERTION"] = (False, tok)
  | tok `Set.member` licenseIds || tok `Set.member` exceptionIds = (True, tok)
  | Just base <- orLater, base `Set.member` licenseIds = (True, tok)
  | tok `Set.member` deprecatedIds, Just replacement <- deprecatedReplacement = (True, replacement)
  | any (`T.isPrefixOf` tok) ["LicenseRef-", "DocumentRef-"] = (False, tok)
  | otherwise = (False, "LicenseRef-" <> T.map idChar tok)
  where
    upper = T.map toUpper tok
    orLater = T.stripSuffix "+" tok
    deprecatedReplacement =
      let candidates = case orLater of
            Just base -> [base <> "-or-later"]
            Nothing -> [tok <> "-only"]
       in case filter (`Set.member` licenseIds) candidates of
            c : _ -> Just c
            [] -> Nothing
    idChar c = if isAscii c && (isAlphaNum c || c == '.' || c == '-') then c else '-'

tokens :: Text -> [Text]
tokens = T.words . T.concatMap spaced
  where
    spaced = \case
      '(' -> " ( "
      ')' -> " ) "
      c -> T.singleton c

untokens :: [Text] -> Text
untokens = T.replace " )" ")" . T.replace "( " "(" . T.unwords

expressionIds :: Text -> [Text]
expressionIds =
  map (\t -> fromMaybe t (T.stripSuffix "+" t))
    . filter (`notElem` ["AND", "OR", "WITH", "(", ")"])
    . map (\t -> if T.map toUpper t `elem` ["AND", "OR", "WITH"] then T.map toUpper t else t)
    . tokens

data FromText
  = NoText
  | Unclear Text
  | Reads [Text]
  deriving stock (Eq, Show)

fromFiles :: Ids -> [(FilePath, [[Text]])] -> FromText
fromFiles Ids {..} identified
  | null groups = NoText
  | any ((> 1) . length) groups = Unclear (describeGroups groups)
  | not (null strays) =
      Unclear
        ( describeGroups groups
            <> ", and there's no telling which license "
            <> T.intercalate ", " (nubOrd (sort strays))
            <> " goes with"
        )
  | otherwise = Reads (nubOrd (sort (withPieces <> plain)))
  where
    groups = nubOrd (concatMap snd identified)
    perFile = [partition (`Set.member` exceptionIds) (nubOrd (concat gs)) | (_, gs) <- identified]
    allLicenses = nubOrd (sort (concatMap snd perFile))
    attached = concatMap attach perFile
    attach (exceptions, licenses) = case (exceptions, licenses, allLicenses) of
      ([], _, _) -> []
      (_, [l], _) -> [Right (l, e) | e <- exceptions]
      (_, [], [l]) -> [Right (l, e) | e <- exceptions]
      _ -> map Left exceptions
    strays = [e | Left e <- attached]
    pairs = [p | Right p <- attached]
    withPieces = [l <> " WITH " <> e | (l, e) <- pairs]
    plain = [l | l <- allLicenses, l `notElem` map fst pairs]

describeGroups :: [[Text]] -> Text
describeGroups groups = "reads as " <> T.intercalate ", " (map (T.intercalate " or ") groups)

hasNoLicense :: Text -> Bool
hasNoLicense e = any (`elem` ["NONE", "NOASSERTION"]) (tokens e)