packages feed

tavro-0.1.0.2: app/Main.hs

{-# LANGUAGE ApplicativeDo #-}

-- ApplicativeDo lets optsP use do-notation even though optparse's Parser
-- is only an Applicative, not a Monad
module Main (main) where

import Control.Concurrent (forkIO, getNumCapabilities)
import Control.Concurrent.MVar (modifyMVar, newEmptyMVar, newMVar, putMVar, takeMVar)
import Control.Exception (IOException, evaluate, try)
import Control.Monad (forM, forM_, replicateM_, unless, when)
import Data.ByteString qualified as BS
import Data.ByteString.Lazy qualified as LBS
import Data.List (isPrefixOf, sort, stripPrefix)
import Data.Map.Strict qualified as Map
import Data.Maybe (catMaybes, fromMaybe, isNothing)
import Data.Text (Text)
import Data.Text qualified as T
import Data.Text.IO qualified as TIO
import Data.Version (showVersion)
import GHC.IO.Encoding (setFileSystemEncoding, setForeignEncoding, setLocaleEncoding)
import Options.Applicative
import Paths_tavro (version)
import System.Directory (doesDirectoryExist, doesFileExist, getFileSize, listDirectory, pathIsSymbolicLink)
import System.Exit (ExitCode (..), exitWith)
import System.FilePath (addTrailingPathSeparator, (</>))
import System.IO (hIsTerminalDevice, hPutStrLn, hSetEncoding, mkTextEncoding, stderr, stdin, stdout)
import Tavro.Cabal
import Tavro.Identify
import Tavro.LicenseList
import Tavro.Match (matcherWarnings)
import Tavro.Report
import Tavro.Spdx (hasNoLicense, idsFromEntries)
import Tavro.Stack
import Tavro.Submodules
import Tavro.Text (decodeLenient)

exitNoMatch, exitUsage :: ExitCode
exitNoMatch = ExitFailure 1
exitUsage = ExitFailure 2

data Action
  = Identify [FilePath]
  | Explain Text [FilePath]
  | List
  | Project Tool FilePath
  | Submodules FilePath

data Tool = CabalTool | StackTool

data CabalOpts = CabalOpts
  { coComponents :: [Text],
    coPackageDbs :: [FilePath],
    coBuilddir :: FilePath,
    coFormat :: CabalFormat,
    coStackArgs :: [String],
    coTests :: Bool
  }

data Opts = Opts
  { optAction :: Action,
    optSearch :: Search,
    optDeprecated :: Bool,
    optNoExceptions :: Bool,
    optOnly :: [Text],
    optData :: Maybe FilePath,
    optFormat :: Format,
    optCabal :: CabalOpts
  }

optsP :: Parser Opts
optsP = do
  optSearch <-
    flag' WholeOnly (long "whole" <> short 'w' <> help "only report licenses that are the whole file, never ones found inside it")
      <|> flag' Everything (long "inside" <> short 'i' <> help "also look for licenses inside the file when it's a license as a whole, like an exception after a GPL")
      <|> pure Auto
  optDeprecated <- switch (long "deprecated" <> hidden <> help "match deprecated ids too, like GPL-2.0 next to GPL-2.0-only")
  optNoExceptions <- switch (long "no-exceptions" <> hidden <> help "leave out license exceptions")
  optOnly <- many (strOption (long "license" <> hidden <> short 'l' <> metavar "ID" <> completeWith licenseIds <> help "only try this license, repeatable"))
  optData <- optional (strOption (long "data" <> hidden <> metavar "DIR" <> action "directory" <> help "use a spdx/license-list-data checkout instead of the license list built in"))
  optFormat <-
    option (eitherReader format) (long "format" <> hidden <> short 'f' <> metavar "FORMAT" <> help "text (default) or json")
      <|> flag' Json (long "json" <> help "same as --format json")
      <|> pure Text
  list <- switch (long "list" <> hidden <> help "list the license and exception ids that can be matched")
  cabal <- switch (long "cabal" <> hidden <> help "list the licenses of the Hackage packages linked into a cabal project's executables, like %cargo_license_online does for crates. FILE is the project directory, . by default, and it needs a build plan, from cabal build or cabal build --dry-run")
  stack <- switch (long "stack" <> hidden <> help "the same for a stack project, from stack ls dependencies")
  submodules <- switch (long "submodules" <> hidden <> help "list the licenses of a git checkout's submodules, nested ones too, from the license files at each one's top. FILE is the checkout, . by default, and its submodules need to be checked out, like with git submodule update --init --recursive")
  coFormat <-
    flag' Summary (long "summary" <> hidden <> help "with --cabal, --stack, or --submodules, only the licenses, one per line, like %cargo_license_summary_online")
      <|> flag' Preamble (long "preamble" <> hidden <> help "with --cabal, --stack, or --submodules, the licenses joined with AND for a spec's License:, like %cargo_license_preamble_online")
      <|> pure PerPackage
  coComponents <- many (strOption (long "component" <> hidden <> short 'c' <> metavar "NAME" <> help "with --cabal, look at this component, like exe:tavro, instead of every executable. repeatable"))
  coPackageDbs <- many (strOption (long "package-db" <> hidden <> metavar "DIR" <> action "directory" <> help "with --cabal or --stack, also look for installed packages here first"))
  coStackArgs <- many (strOption (long "stack-option" <> hidden <> metavar "ARG" <> help "with --stack, pass this to stack, like --stack-option=--system-ghc. repeatable"))
  coTests <- switch (long "test" <> hidden <> help "with --stack, count the project's test suites too")
  coBuilddir <- strOption (long "builddir" <> hidden <> metavar "DIR" <> action "directory" <> value "dist-newstyle" <> showDefault <> help "with --cabal, the project's build directory")
  explainId <- optional (strOption (long "explain" <> metavar "ID" <> completeWith licenseIds <> help "say where each FILE stops matching license ID"))
  files <- many (strArgument (metavar "FILE..." <> action "file" <> help "files or directories to identify, - for stdin (the default)"))
  pure Opts {optAction = pickAction list cabal stack submodules explainId files, optCabal = CabalOpts {..}, ..}
  where
    licenseIds = map (T.unpack . eId) (llEntries embedded)
    pickAction list cabal stack submodules explainId files
      | list = List
      | submodules = Submodules (projectDir files)
      | cabal = Project CabalTool (projectDir files)
      | stack = Project StackTool (projectDir files)
      | otherwise = maybe (Identify files) (`Explain` files) explainId
    projectDir = \case
      d : _ -> d
      [] -> "."
    format = \case
      "text" -> Right Text
      "json" -> Right Json
      other -> Left ("unknown format " <> other <> ", expected text or json")

data Input = Input
  { inPath :: FilePath,
    inOrigin :: Origin
  }

data Origin = NamedOnCommandLine | FoundInDirectory | CouldNotList String
  deriving stock (Eq)

data Contents = Unreadable String | SkippedBinary | SkippedLarge Integer | Contents Text

largestFoundFile :: Integer
largestFoundFile = 10 * 1024 * 1024

-- | a directory stands for the files under it. hidden files and
-- directories are skipped, like .git, and so are symlinked directories,
-- which could loop
expand :: FilePath -> IO [Input]
expand path = do
  isDir <- if path == "-" then pure False else doesDirectoryExist path
  if isDir then walk path else pure [Input path NamedOnCommandLine]
  where
    walk dir =
      try (listDirectory dir) >>= \case
        Left (e :: IOException) -> pure [Input dir (CouldNotList (show e))]
        Right listed -> fmap concat . forM (sort (filter (not . ("." `isPrefixOf`)) listed)) $ \name -> do
          let p = dir </> name
          kind <- try ((,) <$> doesDirectoryExist p <*> pathIsSymbolicLink p)
          case kind of
            Left (e :: IOException) -> pure [Input p (CouldNotList (show e))]
            Right (True, True) -> pure []
            Right (True, False) -> walk p
            Right (False, True) -> do
              target <- doesFileExist p
              pure [Input p FoundInDirectory | target]
            Right _ -> pure [Input p FoundInDirectory]

-- | a binary file found in a directory can't be a license text, so it's
-- skipped, and so is a huge one, which is generated code or data far more
-- often than a license. license files aren't always UTF-8, and a lone
-- Latin-1 byte shouldn't stop the rest of the file from matching
readInput :: Input -> IO Contents
readInput Input {inOrigin = CouldNotList err} = pure (Unreadable err)
readInput Input {..} = do
  size <- if inOrigin == FoundInDirectory then either (\(_ :: IOException) -> 0) id <$> try (getFileSize inPath) else pure 0
  if size > largestFoundFile
    then pure (SkippedLarge size)
    else do
      r <- try (if inPath == "-" then BS.getContents else BS.readFile inPath)
      pure $ case r of
        Left (e :: IOException) -> Unreadable (show e)
        Right bytes
          | inOrigin == FoundInDirectory && BS.elem 0 (BS.take 8000 bytes) -> SkippedBinary
          | otherwise -> Contents (decodeLenient bytes)

useUtf8Everywhere :: IO ()
useUtf8Everywhere = do
  utf8Roundtrip <- mkTextEncoding "UTF-8//ROUNDTRIP"
  mapM_ ($ utf8Roundtrip) [setLocaleEncoding, setFileSystemEncoding, setForeignEncoding]
  mapM_ (`hSetEncoding` utf8Roundtrip) [stdout, stderr]

usageError :: String -> IO a
usageError msg = hPutStrLn stderr ("tavro: " <> msg) >> exitWith exitUsage

main :: IO ()
main = do
  useUtf8Everywhere
  Opts {..} <-
    customExecParser
      defaultPrefs
      ( info
          (optsP <**> helper <**> simpleVersioner ("tavro " <> showVersion version))
          (fullDesc <> failureCode 2 <> progDesc "Identify SPDX licenses by their text, following the SPDX license matching guidelines" <> footer "exit status: 0 when every file matched, 1 when one didn't, 2 on errors")
      )
  let CabalOpts {..} = optCabal
      tool = case optAction of
        Project t _ -> Just t
        _ -> Nothing
      isStack = case tool of
        Just StackTool -> True
        _ -> False
      isSubmodules = case optAction of
        Submodules _ -> True
        _ -> False
  when (isNothing tool && not isSubmodules && coFormat /= PerPackage) $
    usageError "--summary and --preamble go with --cabal, --stack, or --submodules"
  when (isNothing tool && (not (null coComponents) || not (null coPackageDbs))) $
    usageError "--component and --package-db go with --cabal or --stack"
  when (not isStack && (not (null coStackArgs) || coTests)) $
    usageError "--stack-option and --test go with --stack"
  when (isStack && not (null coComponents)) $
    usageError "stack lists packages, not components, so --component goes with --cabal. --test counts the test suites"
  stdinIsTty <- hIsTerminalDevice stdin
  let noFiles = case optAction of
        Identify [] -> True
        Explain _ [] -> True
        _ -> False
  when (noFiles && stdinIsTty) $
    usageError "give files or directories to identify, or pipe text in (see --help)"
  ll <- case optData of
    Nothing -> pure embedded
    Just dir -> fromDirectory dir >>= either usageError pure
  let opts =
        Options
          { oSearch = optSearch,
            oDeprecated = optDeprecated,
            oExceptions = not optNoExceptions,
            oOnly = optOnly,
            oParallel = True
          }
      known = map eId (llEntries ll)
  forM_ optOnly $ \i ->
    unless (i `elem` known) $ usageError (T.unpack i <> " isn't a license or exception id in license list " <> T.unpack (llVersion ll))
  case optAction of
    List -> forM_ (selectEntries opts ll) $ \e ->
      TIO.putStrLn (eId e <> "\t" <> eName e)
    Identify paths -> do
      -- text goes out as files finish, so a big tree shows progress. json
      -- is one document, so it waits for the end
      (results, failed) <-
        forEachInput
          paths
          (\alone path txt -> FileResult path (identify opts {oParallel = alone} ll txt))
          (length . frHits)
          (\r -> when (optFormat == Text) $ TIO.putStr (renderText [r]))
      when (optFormat == Json) $ LBS.putStr (render Json (llVersion ll) results)
      finish (any (null . frHits) results, failed)
    Explain lid paths -> do
      entry <- case [e | e <- llEntries ll, eId e == lid] of
        e : _ -> pure e
        [] -> usageError (T.unpack lid <> " isn't a license or exception id in license list " <> T.unpack (llVersion ll))
      forM_ (matcherWarnings (eMatcher entry)) $ \w ->
        hPutStrLn stderr ("tavro: " <> T.unpack lid <> " template: " <> T.unpack w)
      (verdicts, failed) <-
        forEachInput
          paths
          (\_ path txt -> (path, explain entry txt))
          (\(_, x) -> x `seq` 0)
          (\(path, x) -> TIO.putStrLn (T.pack path <> ": " <> describe lid x))
      finish (any ((/= Matches) . snd) verdicts, failed)
    Project t dir -> projectLicenses t opts ll optFormat optCabal dir
    Submodules dir -> submoduleLicenses opts ll optFormat coFormat dir
  where
    finish (anyUnmatched, failed)
      | failed = exitWith exitUsage
      | anyUnmatched = exitWith exitNoMatch
      | otherwise = pure ()

-- | run a pure check over every input on a pool of workers, one per
-- core, and emit the results in order as they're ready. a file that can't
-- be read is reported and skipped, and the Bool says whether any were
forEachInput :: [FilePath] -> (Bool -> FilePath -> Text -> a) -> (a -> Int) -> (a -> IO ()) -> IO ([a], Bool)
forEachInput paths check force emit = do
  inputs <- concat <$> mapM expand (if null paths then ["-"] else paths)
  let alone = length inputs == 1
  slots <- mapM (const newEmptyMVar) inputs
  queue <- newMVar (zip inputs slots)
  workers <- getNumCapabilities
  let worker =
        modifyMVar queue (\case [] -> pure ([], Nothing); j : js -> pure (js, Just j)) >>= \case
          Nothing -> pure ()
          Just (input, slot) -> do
            outcome <-
              readInput input >>= \case
                Unreadable err -> pure (Failed ("can't read " <> inPath input <> ": " <> err))
                SkippedBinary -> pure Skipped
                SkippedLarge size ->
                  pure (SkippedWithNote (inPath input <> " is " <> show (size `div` (1024 * 1024)) <> " MiB, so it's skipped. name it on the command line to check it anyway"))
                Contents txt -> do
                  let r = check alone (inPath input) txt
                  _ <- evaluate (force r)
                  pure (Done r)
            putMVar slot outcome
            worker
  replicateM_ workers (forkIO worker)
  outcomes <- forM slots $ \slot -> do
    outcome <- takeMVar slot
    case outcome of
      Failed msg -> hPutStrLn stderr ("tavro: " <> msg)
      SkippedWithNote msg -> hPutStrLn stderr ("tavro: " <> msg)
      Skipped -> pure ()
      Done r -> emit r
    pure outcome
  pure ([r | Done r <- outcomes], not (null [() | Failed _ <- outcomes]))

data Outcome a = Failed String | Skipped | SkippedWithNote String | Done a

-- | what %cargo_license_online and friends do for crates, for the
-- Hackage packages a cabal or stack project links in. notes go to stderr,
-- and like those macros, only real errors fail
projectLicenses :: Tool -> Options -> LicenseList -> Format -> CabalOpts -> FilePath -> IO ()
projectLicenses tool opts ll fmt CabalOpts {..} dir = do
  (packages, toolchain) <- case tool of
    CabalTool -> do
      plan <- readPlan (dir </> coBuilddir </> "cache" </> "plan.json") >>= either usageError pure
      units <- either usageError pure (linkedUnits coComponents plan)
      toolchain <- findToolchain coPackageDbs plan
      pure (packagesOf units, toolchain)
    StackTool -> do
      deps <- stackDependencies dir coStackArgs coTests >>= either usageError pure
      toolchain <- stackToolchain dir coStackArgs >>= either usageError pure
      let toolchain' = toolchain {tDbs = coPackageDbs <> tDbs toolchain}
      packages <- stackPackages (tDbs toolchain') deps
      pure (packages, toolchain')
  when (null (tDbs toolchain)) $
    hPutStrLn stderr "tavro: found no package databases, so only the project's own packages have licenses. see --package-db"
  licenses <- gatherLicenses toolchain packages
  judged <- forM licenses $ \pl -> do
    identified <- identifyLicenseFiles opts ll (plFiles pl)
    let v = judge (idsFromEntries (llEntries ll)) pl identified
    forM_ (vNotes v) $ \note ->
      hPutStrLn stderr ("tavro: " <> T.unpack (pName (vPackage v) <> "-" <> pVersion (vPackage v) <> ": " <> note))
    pure (v, plDeclared pl, plFiles pl)
  case fmt of
    Json -> LBS.putStr (renderCabalJson (llVersion ll) judged)
    Text -> do
      let verdicts = [v | (v, _, _) <- judged]
      when (coFormat == Preamble) $ refuseUnlicensed (\p -> pName p <> "-" <> pVersion p) verdicts
      TIO.putStr (renderCabal coFormat verdicts)

submoduleLicenses :: Options -> LicenseList -> Format -> CabalFormat -> FilePath -> IO ()
submoduleLicenses opts ll fmt cfmt dir = do
  (subs, missing) <- listSubmodules dir >>= either usageError pure
  forM_ missing $ \path ->
    hPutStrLn stderr ("tavro: " <> path <> " isn't checked out, so it's left out. run git submodule update --init --recursive")
  when (null subs && null missing) $
    hPutStrLn stderr ("tavro: " <> dir <> " has no submodules")
  judged <- forM subs $ \sub -> do
    files <- submoduleLicenseFiles (dir </> sPath sub)
    identified <- identifyLicenseFiles opts ll files
    let v = judgeSubmodule (idsFromEntries (llEntries ll)) sub identified
    forM_ (vNotes v) $ \note ->
      hPutStrLn stderr ("tavro: " <> sPath sub <> ": " <> T.unpack note)
    pure (v, map (makeRelativeTo dir) files)
  case fmt of
    Json -> LBS.putStr (renderSubmodulesJson (llVersion ll) judged missing)
    Text -> unless (null judged) $ do
      when (cfmt == Preamble) $ refuseUnlicensed pName (map fst judged)
      TIO.putStr (renderSubmodules cfmt (map fst judged))
  where
    makeRelativeTo base path = fromMaybe path (stripPrefix (addTrailingPathSeparator base) path)

refuseUnlicensed :: (Package -> Text) -> [Verdict] -> IO ()
refuseUnlicensed label verdicts =
  case [label (vPackage v) <> " (" <> vExpression v <> ")" | v <- verdicts, hasNoLicense (vExpression v)] of
    [] -> pure ()
    unlicensed -> do
      hPutStrLn stderr ("tavro: no License: tag without a license for " <> T.unpack (T.intercalate ", " unlicensed))
      exitWith exitNoMatch

identifyLicenseFiles :: Options -> LicenseList -> [FilePath] -> IO [(FilePath, [[Text]])]
identifyLicenseFiles opts ll files = fmap catMaybes . forM files $ \f -> do
  r <- readInput (Input f FoundInDirectory)
  pure $ case r of
    Contents txt -> Just (f, indistinguishableIds (identify opts ll txt))
    _ -> Nothing
  where
    indistinguishableIds hits = Map.elems (Map.fromListWith (flip (<>)) [((hHow h, hSpan h), [eId (hEntry h)]) | h <- hits])

describe :: Text -> Explanation -> Text
describe lid = \case
  Matches -> "matches " <> lid
  MissingWords ws ->
    "doesn't match "
      <> lid
      <> ", it's missing words the license needs: "
      <> T.intercalate ", " (take 12 ws)
      <> (if length ws > 12 then ", ..." else "")
  Differs {..} ->
    "doesn't match "
      <> lid
      <> " from line "
      <> T.pack (show xLine)
      <> "\n  expected: "
      <> T.unwords xExpected
      <> "\n  found:    "
      <> xFound