packages feed

fbrnch-1.8.4: src/Cmd/ReviewPackage.hs

{-# LANGUAGE CPP, OverloadedStrings #-}

module Cmd.ReviewPackage (
  reviewPackage
  ) where

import Common
import Common.System

import Data.Char
import Data.Either (isRight)
import Data.Tuple.Extra (second)
import Safe (headDef, headMay, lastMay, tailSafe)
import SelectRPMs (selectDefault, Yes(No))
import SimplePrompt (promptEnter, yesNoDefault)
import System.Console.Pretty (color, Color(Red))

import Branches
import Bugzilla
import Cmd.Import (downloadReviewSRPM, upstreamDir)
import Cmd.Install (installCmd)
import Cmd.Local (localCmd)
import Cmd.Prep (prepCmd)
import Git (isGitDirClean, isGitRepo, git_, gitBool)
import Package
import RpmBuild

-- FIXME does not work with pkg dir/spec: 'fbrnch: No spec file found'
-- FIXME --user to download all user's review requests
reviewPackage :: Bool -> Bool -> Bool -> Maybe String -> IO ()
reviewPackage dryrun full update Nothing = do
  -- FIXME catch no spec file
  spec <- findSpecfile
  srpm <- generateSrpm Nothing spec
  if not full
    then
    if update
    then reviewPackage dryrun full update (Just $ takeBaseName spec)
    else doInteractiveReview dryrun update (Just spec) srpm
    else do
    cmd_ "fedora-review" ["-rn", srpm]
reviewPackage dryrun full update (Just pkgbug) = do
  let epkgbid =
        if all isDigit pkgbug
        then Right $ read pkgbug
        else Left pkgbug
  (bugs,session) <- bugsSession $
          case epkgbid of
            Right bid -> packageReview .&&. bugIdIs bid
            Left pkg -> pkgReviews pkg .&&. statusNewAssigned
  case bugs of
    [bug] -> do
      putReviewBug False bug
      when (isRight epkgbid) $
        unless (bugStatus bug `elem` ["NEW", "ASSIGNED"]) $ do
        putStrLn "Warning: review is past NEW/ASSIGNED state!"
        promptEnter "Press Enter to continue anyway"
      let bid = bugId bug
          pkg = reviewBugToPackage bug
      if not full
        then reviewPackageInteractive dryrun update bid pkg session bug
        else do
        promptEnter "Press Enter to run fedora-review"
        -- FIXME support copr build
        -- FIXME if toolbox set REVIEW_NO_MOCKGROUP_CHECK
        cmd_ "fedora-review" ["-b", show bid]
    [] -> error' $ "No package review found for" +-+ pkgbug
    _ -> error' $ "More than one review bug found for" +-+ pkgbug

reviewPackageInteractive :: Bool -> Bool -> Int -> String
                         -> BugzillaSession -> Bug -> IO ()
reviewPackageInteractive dryrun update bid pkg session bug = do
  let dir = show bid ++ '-' : pkg
  -- FIXME check if current directory
  exists <- doesDirectoryExist dir
  unless update $ do
    unless exists $
      createDirectory dir
    setCurrentDirectory dir
  srpm <- downloadReviewSRPM True True False update pkg bid session
  importsrpm <-
    if update
    then return True
    else
      if exists
      then do
        putStrLn $ "in" +-+ dir </> ":\n"
        cmd_ "ls" ["-F"]
        putNewLn
        -- FIXME default to no if nvr unchanged?
        yesNoDefault True "Press Enter to install/prep srpm"
      else return True
  -- review and package name may be different (eg ramalama)
  doInteractiveReview dryrun importsrpm Nothing srpm
  putNewLn
  putReviewBug False bug
  putNewLn
  putStrLn $ "Review dir is" +-+ dir

doInteractiveReview :: Bool -> Bool -> Maybe FilePath -> FilePath -> IO ()
doInteractiveReview dryrun importsrpm mspec srpm = do
  when importsrpm $ do
    isgit <- isGitRepo
    if isgit
      then
      unlessM isGitDirClean $
      promptEnter "git dir not clean: commit and Press Enter"
      else git_ "init" []
    -- FIXME override %_sourcedir so it doesn't put elsewhere?
    sourcediropt <- sourceDirCwdOpt
    putStrLn "installing srpm:"
    cmd_ "rpm" $ ["-i", srpm] ++ sourcediropt
    spec <- maybe findSpecfile return mspec
    git_ "add" [spec]
    allsrcs <- map sourceFieldFile <$> cmdLines "spectool" [spec]
    forM_ allsrcs $ \src ->
      unless (isArchiveFile src) $
      git_ "add" [src]
    putStrLn $ "# Diff with" +-+ upstreamDir
    void $ cmdBool "diff" ["-u", spec, upstreamDir </> spec]
    withCurrentDirectory upstreamDir $
      cmd_ "spectool" ["-g", spec]
    diff <- lines <$> cmdIgnoreErr "diff" ["--brief", ".", upstreamDir] ""
    let filterdiff = filter (\d -> not (any (`isSuffixOf` d) ["SPEC","SRPMS","RPMS","BUILD","BUILDROOT","src.rpm",".log", ".git", upstreamDir])) diff
    if null filterdiff
      then putStrLn $ "no difference with" +-+ upstreamDir ++ "/"
      else do
      let colorDiffer cs =
            case lastMay $ words cs of
              Just l | l == "differ" -> color Red cs
              _ -> cs
      mapM_ (putStrLn . colorDiffer) filterdiff
    unlessM (gitBool "diff" ["--quiet", "--cached"]) $
      git_ "commit" ["-m", srpm]
  putNewLn
  putStrLn "# Build"
  -- FIXME or download rpms
  build <- yesNoDefault importsrpm "Build package locally"
  if build
    then localCmd dryrun False False False Nothing Nothing [] (Branches [],[])
    else do
    putStr "prep "
    prepCmd dryrun Nothing False False False (Nothing,[])
  putNewLn
  putStrLn "# RpmLint"
  spec <- maybe findSpecfile return mspec
  br <- systemBranch
  built <- builtRpms (RelBranch br) spec
  void $ cmdBool "rpmlint" $ spec : srpm : built
  whenM (yesNoDefault importsrpm "Install packages locally") $ do
    installCmd dryrun False False Nothing Nothing Nothing [] Nothing False False True True No selectDefault Nothing (Nothing,[])
    rpms <- cmdLines "rpmspec" ["-q", "--rpms", "--qf", "%{name}\n", spec]
    whenM (yesNoDefault importsrpm "Rpmlint installed packages") $ do
       (_ok, out, err) <- cmdFull "rpmlint" ("-i" : rpms) ""
       let rpmlintout = "rpmlint.output"
       writeFile rpmlintout out
       let ls = lines out
           nolines = length ls
       if nolines > 20
         then do
         mapM_ putStrLn $ takeEnd 10 ls
         putNewLn
         putStrLn "RpmLint summary:"
         mapM_ (putStrLn . renderLintSummary) $ summarizeErrors ls
         putStrLn $ show nolines +-+ "lines saved to" +-+ rpmlintout
         else putStrLn out
       unless (null err) $ warning $ "rpmlint stderr:\n" ++ err
       putNewLn
  putStrLn "# Licensing"
  whenM (yesNoDefault True "Run licensecheck") $ do
    buildls <- listDirectory "BUILD"
    builddir <-
      case sort buildls of
        [] -> error' "empty BUILD/"
        [d] -> return $ "BUILD" </> d
        -- FIXME not good enough! use nvr
        ds -> return $ "BUILD" </> last ds
    builddirls <- listDirectory builddir >>= filterM (doesDirectoryExist . (builddir +/+))
    builddir2 <-
      case sort $ builddirls \\ ["BUILDROOT","SPECPARTS",".pyproject-builddir","pyproject-wheeldir"]  of
        [] -> error' $ "empty" +-+ "BUILD" </> builddir
        [d] -> return $ builddir </> d
        -- FIXME? some projects might have more than one topdir
        ds -> error' $ "more than one dir:" +-+ unwords ds
    let args = ["--shortname-scheme", "spdx", "-r", builddir2]
    cmdN "licensecheck" args
    cmdLines "licensecheck" args >>=
      -- handle "FILEPATH: *No copyright* UNKNOWN [generated file]"
      mapM_ putStrLn . filter (not . (" UNKNOWN" `isInfixOf`))
  cmd_ "rpmspec" ["-q", "--srpm", "--qf", "Spec license: %{license}\n", spec]

summarizeErrors :: [String] -> [(String,Int)]
summarizeErrors =
  sortOn fst . map (second length) . groupOnKey (headDef "''") . map tailSafe . filter ((Just "E:" ==) . headMay) . map (tailSafe . words)

renderLintSummary :: (String,Int) -> String
renderLintSummary (err,n) = err ++ ":" +-+ show n

#if !MIN_VERSION_extra(1,7,11)
groupOnKey :: Eq k => (a -> k) -> [a] -> [(k, [a])]
groupOnKey _ []     = []
groupOnKey f (x:xs) = (fx, x:yes) : groupOnKey f no
    where
        fx = f x
        (yes, no) = span (\y -> fx == f y) xs
#endif