hooky-1.0.9: src/Hooky/Lint.hs
{-# LANGUAGE DuplicateRecordFields #-}
{-# LANGUAGE LambdaCase #-}
{-# LANGUAGE OverloadedRecordDot #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE TupleSections #-}
{-# LANGUAGE NoFieldSelectors #-}
module Hooky.Lint (
LintOptions (..),
LintReport (..),
LintResult (..),
runLintRules,
renderLintReport,
lintReportSuccess,
-- * Re-exports from "Hooky.Config"
LintRule (..),
LintRuleRule (..),
toGlob,
) where
import Control.DeepSeq (NFData (..))
import Control.Monad (forM, when)
import Data.Bifunctor (first)
import Data.Char (isSpace)
import Data.Foldable (foldlM)
import Data.List.NonEmpty (NonEmpty)
import Data.List.NonEmpty qualified as NonEmpty
import Data.Map (Map)
import Data.Map qualified as Map
import Data.Maybe (catMaybes)
import Data.Set qualified as Set
import Data.Text (Text)
import Data.Text qualified as Text
import Data.Text.Encoding qualified as Text
import Hooky.Config (
Config (..),
LintRule (..),
LintRuleRule (..),
RepoConfig (..),
)
import Hooky.Internal.GitFile (GitFile, resolveGitFiles)
import Hooky.Internal.GitFile qualified as GitFile
import Hooky.Internal.Logging qualified as Logging
import Hooky.Utils.Git (GitClient)
import Hooky.Utils.Glob (Glob, matchesGlobs, toGlob)
import Hooky.Utils.OsPath qualified as OsPath
import System.File.OsPath qualified as OsPath
import System.IO.Error (isDoesNotExistError)
import System.OsPath (OsPath)
import UnliftIO.Exception (evaluateDeep, tryJust)
data LintOptions = LintOptions
{ autofix :: Bool
, files :: Map OsPath GitFile
}
{----- runLintRules -----}
runLintRules :: GitClient -> Config -> LintOptions -> IO LintReport
runLintRules git config options = do
let allLinters =
[ (rule, fromLintRule rule)
| rule <- config.repo.lintRules
, rule.name `Set.notMember` config.skippedHooks
]
nonFileLintResults <- runNonFileLintRules git allLinters
allFilesLintResults <- runAllFilesLintRules git allLinters
fileLintResults <-
mapM (runPerFileLintRules git options allLinters) $
[ file
| GitFile.GitFile file <- Map.elems options.files
]
let report =
Map.unionsWith (<>) $
[ Map.mapMaybe NonEmpty.nonEmpty $ Map.singleton Nothing nonFileLintResults
, allFilesLintResults
, Map.mapMaybe NonEmpty.nonEmpty $ Map.fromList fileLintResults
]
evaluateDeep $ LintReport report
type RuleName = Text
runNonFileLintRules ::
GitClient ->
[(LintRule, LintAction)] ->
IO [(RuleName, LintResult)]
runNonFileLintRules git allLinters =
forM linters $ \(rule, run) -> do
Logging.debug $ "Running linter: " <> rule.name
result <- run git
pure (rule.name, result)
where
linters = [(rule, run) | (rule, LintActionNoFile run) <- allLinters]
runAllFilesLintRules ::
GitClient ->
[(LintRule, LintAction)] ->
IO (Map (Maybe OsPath) (NonEmpty (RuleName, LintResult)))
runAllFilesLintRules git allLinters = do
files <- resolveGitFiles git GitFile.FilesAll
fmap (Map.unionsWith (<>)) . forM linters $ \(rule, run) -> do
Logging.debug $ "Running linter: " <> rule.name
failures <- run git $ Map.filterWithKey (isIncluded rule) files
let results =
if null failures
then [(Nothing, LintSuccess)]
else [(Just fp, LintFailed msg) | (fp, msg) <- failures]
pure . Map.fromList $
[ (fp, NonEmpty.singleton (rule.name, result))
| (fp, result) <- results
]
where
linters = [(rule, run) | (rule, LintActionAllFiles run) <- allLinters]
isIncluded rule path _ = matchesGlobs rule.fileGlobs (OsPath.toText path)
runPerFileLintRules ::
GitClient ->
LintOptions ->
[(LintRule, LintAction)] ->
OsPath ->
IO (Maybe OsPath, [(RuleName, LintResult)])
runPerFileLintRules git options allLinters file =
-- Skip reading file if there are no per-file linters to run
(if null linters then pure Nothing else readFileMaybe file) >>= \case
Nothing -> pure (Just file, [])
Just contents1 -> do
(results, contents2) <-
mapAndFoldM
( \contents (rule, run) -> do
Logging.debug $ "Running linter: " <> rule.name
(result, contents') <- run git file contents
pure $
if options.autofix
then ((rule.name, result), contents')
-- TODO: show diff of fix failure
else ((rule.name, if result == LintFixed then LintFailed "file would be changed" else result), contents)
)
contents1
linters
when (any ((== LintFixed) . snd) results) $ do
OsPath.writeFile' file (Text.encodeUtf8 contents2)
pure (Just file, results)
where
linters =
[ (rule, run)
| (rule, LintActionPerFile run) <- allLinters
, matchesGlobs rule.fileGlobs . OsPath.toText $ file
]
readFileMaybe fp = do
result <-
tryJust
(\e -> if isDoesNotExistError e then Just e else Nothing)
(OsPath.readFile' fp)
pure $
-- Skip reading non-utf8 files
case result of
Right bs | Right s <- Text.decodeUtf8' bs -> Just s
_ -> Nothing
-- mapM that also threads state through the loop
mapAndFoldM :: (Monad m) => (s -> a -> m (b, s)) -> s -> [a] -> m ([b], s)
mapAndFoldM f s0 as = do
(acc, s') <-
foldlM
( \(acc, s) a -> do
(b, s') <- f s a
pure (b : acc, s')
)
([], s0)
as
pure (reverse acc, s')
{----- LintReport -----}
-- | Map from filepath to the hooks and their results.
newtype LintReport = LintReport
{ unwrap ::
Map
(Maybe OsPath)
(NonEmpty (RuleName, LintResult))
}
deriving (NFData)
lintReportSuccess :: LintReport -> Bool
lintReportSuccess report =
all ((== LintSuccess) . snd)
. (concat . Map.elems . Map.map NonEmpty.toList)
$ report.unwrap
renderLintReport :: LintReport -> Text
renderLintReport report = Text.intercalate "\n\n" $ failureMsgs ++ successMsgs
where
failureMsgs =
[ Text.intercalate "\n" $
(maybe "FAILURES" OsPath.toText mFile <> ":")
: [ "- [" <> hook <> "] " <> msg
| (hook, result) <- NonEmpty.toList results
, Just msg <-
pure $
case result of
LintSuccess -> Nothing
LintFixed -> Just "FIXED"
LintFailed msg -> Just msg
]
| (mFile, results) <- Map.toAscList report.unwrap
, any ((/= LintSuccess) . snd) results
]
successfulHooks = getSuccessfulHooks report
successMsgs =
if null successfulHooks
then []
else [Text.intercalate "\n" $ "Hooks passed:" : map ("- " <>) successfulHooks]
getSuccessfulHooks :: LintReport -> [RuleName]
getSuccessfulHooks report =
-- Map (Maybe OsPath) [(Text, LintResult)]
-- => [(Text, LintResult)]
-- => [(Text, isSuccess)]
-- => Map Text isSuccess
Map.keys
. Map.filter and
. Map.fromListWith (<>)
. map (\(hook, result) -> (hook, [result == LintSuccess]))
. (concat . Map.elems . Map.map NonEmpty.toList)
$ report.unwrap
{----- LintAction -----}
data LintAction
= LintActionNoFile (GitClient -> IO LintResult)
| LintActionAllFiles (GitClient -> Map OsPath GitFile -> IO [(OsPath, FailureMessage)])
| LintActionPerFile (GitClient -> OsPath -> FileContent -> IO (LintResult, FileContent))
type FailureMessage = Text
type FileContent = Text
data LintResult = LintSuccess | LintFixed | LintFailed FailureMessage
deriving (Show, Eq)
instance NFData LintResult where
rnf = \case
LintSuccess -> ()
LintFixed -> ()
LintFailed msg -> rnf msg
fromLintRule :: LintRule -> LintAction
fromLintRule LintRule{rule} =
case rule of
LintRule_CheckBrokenSymlinks -> lint_CheckBrokenSymlinks
LintRule_CheckCaseConflict -> lint_CheckCaseConflict
LintRule_CheckMergeConflict -> lint_CheckMergeConflict
LintRule_EndOfFileFixer -> lint_EndOfFileFixer
LintRule_NoCommitToBranch branches -> lint_NoCommitToBranch branches
LintRule_TrailingWhitespace -> lint_TrailingWhitespace
{----- Lint rule implementations -----}
lint_CheckBrokenSymlinks :: LintAction
lint_CheckBrokenSymlinks = LintActionAllFiles $ \_ files -> do
let filePaths = Map.keysSet files
dirPaths = foldMap (Set.fromList . OsPath.parents) filePaths
pure
[ (link.path, failure)
| GitFile.GitFile_Symlink link <- Map.elems files
, link.target `Set.notMember` (if link.isDir then dirPaths else filePaths)
]
where
failure = "File is a broken symlink. Remove or exclude from rule"
lint_CheckCaseConflict :: LintAction
lint_CheckCaseConflict = LintActionAllFiles $ \_ files -> do
let collisionMap =
Map.fromListWith (<>) $
[ (Text.toLower (OsPath.toText fp), [fp])
| fp <- Map.keys files
]
pure
[ (fp, "File conflicts with: " <> Text.intercalate ", " (map OsPath.toText rest))
| fp : rest@(_ : _) <- Map.elems collisionMap
]
lint_CheckMergeConflict :: LintAction
lint_CheckMergeConflict = LintActionPerFile $ \_ _ contents -> do
let result =
case catMaybes $ zipWith getMergeConflict (Text.lines contents) [1 :: Int ..] of
[] -> LintSuccess
(lineNum, conflictPat) : _ ->
LintFailed $
"Merge conflict string found at line " <> Text.show lineNum <> ": " <> Text.show conflictPat
pure (result, contents)
where
getMergeConflict line lineNum
| pat : _ <- filter (`Text.isPrefixOf` line) prefixMatches = Just (lineNum, pat)
| pat : _ <- filter (== line) fullMatches = Just (lineNum, pat)
| otherwise = Nothing
prefixMatches =
[ "<<<<<<< "
, "======= "
, ">>>>>>> "
]
fullMatches = ["======="]
lint_EndOfFileFixer :: LintAction
lint_EndOfFileFixer = LintActionPerFile $ \_ _ contents -> do
case spanEnd (== '\n') contents of
_ | Text.null contents -> pure (LintSuccess, contents)
(_, suf) | Text.compareLength suf 1 == EQ -> pure (LintSuccess, contents)
(stripped, _) -> pure (LintFixed, stripped <> "\n")
lint_NoCommitToBranch :: [Glob] -> LintAction
lint_NoCommitToBranch branches = LintActionNoFile $ \git -> do
branch <- git.query ["branch", "--show-current"]
pure $
if matchesGlobs branches branch
then LintFailed $ "cannot commit to branch: " <> branch
else LintSuccess
lint_TrailingWhitespace :: LintAction
lint_TrailingWhitespace = LintActionPerFile $ \_ _ contents -> do
let (contents', success) = overLines contents $ \line ->
let (line', noTrailingWs) = spanEnd isSpace line
in (line', Text.null noTrailingWs)
pure (if and success then LintSuccess else LintFixed, contents')
where
-- Avoid unlines/lines, since they implicitly add trailing newline
overLines :: Text -> (Text -> (Text, a)) -> (Text, [a])
overLines s f = first (Text.intercalate "\n") . unzip . map f . Text.splitOn "\n" $ s
{----- Utilities -----}
spanEnd :: (Char -> Bool) -> Text -> (Text, Text)
spanEnd p s =
let suf = Text.takeWhileEnd p s
in (Text.dropEnd (Text.length suf) s, suf)