hooky-1.0.9: src/Main.hs
{-# LANGUAGE ApplicativeDo #-}
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE DuplicateRecordFields #-}
{-# LANGUAGE GADTs #-}
{-# LANGUAGE LambdaCase #-}
{-# LANGUAGE OrPatterns #-}
{-# LANGUAGE OverloadedLabels #-}
{-# LANGUAGE OverloadedRecordDot #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE QuasiQuotes #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE NoFieldSelectors #-}
import Control.Applicative ((<**>), (<|>))
import Control.Monad (guard, unless, when)
import Data.Coerce (coerce)
import Data.Maybe (catMaybes, fromMaybe)
import Data.Proxy (Proxy (..))
import Data.Set (Set)
import Data.Set qualified as Set
import Data.Text (Text)
import Data.Text qualified as Text
import Data.Text.Encoding qualified as Text
import Data.Text.IO qualified as Text
import Data.Text.Lazy qualified as LazyText
import Data.Text.Lazy.IO qualified as LazyText
import Data.Typeable (typeOf, typeRep)
import Data.Version (showVersion)
import Hooky.Config (
Config (..),
GlobalConfig (..),
RunMode (..),
allRunModes,
loadConfig,
parseRunMode,
renderRunMode,
)
import Hooky.Error (abortImpure)
import Hooky.Internal.GitFile (
GitFileTarget,
GitFileTargetArg,
parseGitFileTargetArg,
resolveGitFiles,
)
import Hooky.Internal.GitFile qualified as GitFile
import Hooky.Internal.Logging qualified as Logging
import Hooky.Internal.Messages qualified as Messages
import Hooky.Internal.Output (
OutputFormat (..),
allOutputFormats,
parseOutputFormat,
renderOutputFormat,
)
import Hooky.Lint (
LintOptions (..),
lintReportSuccess,
renderLintReport,
runLintRules,
)
import Hooky.Run (
RunOptions (..),
runHooks,
)
import Hooky.Utils.Git (GitClient (..), initGitClient)
import Hooky.Utils.OsPath qualified as OsPath
import Hooky.Utils.Term qualified as Term
import Options.Applicative qualified as Opt
import Options.Applicative.Types qualified as Opt.Internal
import Paths_hooky qualified
import System.Directory.OsPath (
doesFileExist,
getPermissions,
makeAbsolute,
renameFile,
setPermissions,
)
import System.Directory.OsPath qualified as Permissions (Permissions (..))
import System.Environment (getExecutablePath)
import System.Exit (ExitCode, exitFailure)
import System.File.OsPath qualified as OsPath
import System.IO qualified as IO
import System.OsPath (OsPath, addExtension, osp, (</>))
import UnliftIO.Exception (Exception (..), SomeException (..), handleJust)
{----- CLI Options -----}
data CLIOptions = CLIOptions
{ run :: CLICommandAction
, configFile :: Maybe OsPath
, verbose :: Bool
}
type CLICommandAction = GitClient -> Config -> IO ()
data CLICommandDef
= forall cmd.
(IsCLICommand cmd) =>
CLICommandDef
{ name :: String
, description :: String
, cmdType :: Proxy cmd
}
class IsCLICommand cmd where
cliCommandParse :: Opt.Parser cmd
cliCommandRun :: Proxy cmd -> cmd -> CLICommandAction
loadCLIOptions :: IO CLIOptions
loadCLIOptions =
Opt.customExecParser prefs $
Opt.info (parseOptions <**> Opt.helper <**> version) . mconcat $
[ Opt.fullDesc
, Opt.header "Hooky: A minimal git hooks manager"
]
where
prefs =
Opt.prefs . mconcat $
[ Opt.subparserInline
]
version =
Opt.infoOption (showVersion Paths_hooky.version) . mconcat $
[ Opt.long "version"
, Opt.help "Print version of hooky"
]
parseOptions = do
run <- parseInternalCommand <|> parseCommand
configFile <-
Opt.optional . Opt.option (OsPath.fromText <$> Opt.str) . mconcat $
[ Opt.long "config"
, Opt.short 'c'
, Opt.help "Path to config file (default: .hooky.kdl)"
]
verbose <-
Opt.switch . mconcat $
[ Opt.long "verbose"
, Opt.short 'v'
, Opt.help "Increase logging verbosity"
]
pure CLIOptions{..}
parseInternalCommand =
Opt.subparser . (Opt.internal <>) . mconcat . map mkCommand $
[ cmdRunGit
]
parseCommand =
Opt.hsubparser . mconcat . map mkCommand $
[ cmdInstall
, cmdRun
, cmdFix
, cmdLint
]
mkCommand CLICommandDef{..} =
Opt.command name $
Opt.info (cliCommandRun cmdType <$> cliCommandParse) $
Opt.progDesc description
{----- Entrypoint -----}
main :: IO ()
main = handleErrors $ do
IO.hSetEncoding IO.stdout IO.utf8
IO.hSetEncoding IO.stderr IO.utf8
cli <- loadCLIOptions
Logging.initialize $
if cli.verbose
then Logging.LogLevel_Debug
else Logging.LogLevel_Warn
git <- initGitClient
repoConfigPath <-
case cli.configFile of
Nothing -> pure $ git.repo </> [osp|.hooky.kdl|]
Just fp -> makeAbsolute fp
config <- loadConfig repoConfigPath
cli.run git config
handleErrors :: IO a -> IO a
handleErrors = handleJust shouldHandle $ \(SomeException e) -> do
LazyText.hPutStrLn IO.stderr . Term.red $ (LazyText.strip . LazyText.pack . displayException) e
exitFailure
where
shouldHandle (SomeException e) = do
guard $ typeOf e `notElem` ignoredErrors
Just (SomeException e)
ignoredErrors =
[ typeRep (Proxy @ExitCode)
]
{----- hooky install -----}
cmdInstall :: CLICommandDef
cmdInstall =
CLICommandDef
{ name = "install"
, description = "Install hooky as the git pre-commit hook"
, cmdType = Proxy @Cmd_Install
}
-- Any flags here should probably be in GlobalConfig too.
data Cmd_Install = Cmd_Install
{ mode :: Maybe RunMode
, format :: Maybe OutputFormat
, useAbsolute :: Bool
}
instance IsCLICommand Cmd_Install where
cliCommandParse = do
mode <- parseRunModeCLI
format <- parseFormatCLI
useAbsolute <-
Opt.switch . mconcat $
[ Opt.long "absolute"
, Opt.help "Whether to install the absolute path to hooky"
]
pure Cmd_Install{..}
cliCommandRun _ cmd git config = do
hookFile <- git.getPath [osp|hooks/pre-commit|]
backupOldHookFile hookFile
let useAbsolute = config.global.useAbsolute || cmd.useAbsolute
hookyExe <-
if useAbsolute
then Text.pack <$> getExecutablePath
else pure "hooky"
let configPath = OsPath.toText config.repoConfigPath
OsPath.writeFile' hookFile . Text.encodeUtf8 . Text.unlines $
[ "hooky_exe=" <> quote hookyExe
, "if ! command -v \"$hooky_exe\" 2>&1 >/dev/null; then"
, if useAbsolute
then " echo >&2 \"Could not find hooky executable: ${hooky_exe}\""
else " echo >&2 'Could not find hooky executable, is it on PATH?'"
, " exit 1"
, "fi"
, Text.unwords . concat $
[ ["exec \"$hooky_exe\" __git"]
, ["--config", quote configPath]
, case cmd.mode of
Just mode -> ["--mode", quote $ renderRunMode mode]
Nothing -> []
, case cmd.format of
Just format -> ["--format", quote $ renderOutputFormat format]
Nothing -> []
]
]
makeExecutable hookFile
LazyText.putStrLn . Term.green $ "🚀 Hooky installed at: " <> OsPath.toLazyText hookFile
where
quote s = "'" <> s <> "'"
makeExecutable fp = do
p <- getPermissions fp
setPermissions fp p{Permissions.executable = True}
backupOldHookFile fp = do
exists <- doesFileExist fp
-- TODO: Don't back up if reinstalling hooky
when exists $ do
let backup = addExtension fp [osp|bak|]
renameFile fp backup
Messages.log . LazyText.unlines $
[ "Found previously installed pre-commit hooks."
, "Backed up to: " <> OsPath.toLazyText backup
]
{----- hooky __git -----}
cmdRunGit :: CLICommandDef
cmdRunGit =
CLICommandDef
{ name = "__git"
, description = "Run as a git hook"
, cmdType = Proxy @Cmd_RunGit
}
data Cmd_RunGit = Cmd_RunGit
{ mode :: Maybe RunMode
, format :: Maybe OutputFormat
}
instance IsCLICommand Cmd_RunGit where
cliCommandParse = do
mode <- parseRunModeCLI
format <- parseFormatCLI
pure Cmd_RunGit{..}
cliCommandRun _ cmd git config = do
runHooks git config $
RunOptions
{ mode = fromMaybe config.global.mode cmd.mode
, hooksToRun = Nothing
, fileTarget = GitFile.FilesStaged
, format = fromMaybe config.global.format cmd.format
, stash = True
}
{----- hooky run ------}
cmdRun :: CLICommandDef
cmdRun =
CLICommandDef
{ name = "run"
, description = "Run hooks"
, cmdType = Proxy @Cmd_Run
}
data Cmd_Run = Cmd_Run
{ mode :: RunMode
, hooksToRun :: Maybe (Set Text)
, fileTarget :: GitFileTarget
, stash :: Bool
, format :: Maybe OutputFormat
}
instance IsCLICommand Cmd_Run where
cliCommandParse = do
hooksToRun <-
Opt.optional . fmap Set.fromList . Opt.some $
Opt.strOption . mconcat $
[ Opt.long "hook"
, Opt.short 'k'
, Opt.help "Hook(s) to run (defaults to all hooks)"
]
mFileTarget <-
cliOneOfOptional $
[ GitFile.FilesGiven <$> parseFilesCLI
, Opt.flag' GitFile.FilesModified . mconcat $
[ Opt.long "modified"
, Opt.short 'm'
, Opt.help "Run on modified files"
]
, Opt.flag' GitFile.FilesStaged . mconcat $
[ Opt.long "staged"
, Opt.short 's'
, Opt.help "Run on staged files"
]
, Opt.flag' GitFile.FilesAll . mconcat $
[ Opt.long "all"
, Opt.short 'a'
, Opt.help "Run on all files"
]
, Opt.flag' GitFile.FilesPrev . mconcat $
[ Opt.long "prev"
, Opt.short '1'
, Opt.help "Run on files modified in the previous commit"
]
]
stashFlag <-
Opt.switch . mconcat $
[ Opt.long "stash"
, Opt.help "Stash unstaged changes before running hooks"
]
format <- parseFormatCLI
pure $
let (fileTarget, stash) =
case mFileTarget of
Nothing -> (GitFile.FilesStaged, True)
Just ft -> (ft, stashFlag)
in Cmd_Run{mode = Mode_Check, ..}
cliCommandRun _ cmd git config = do
runHooks git config $
RunOptions
{ mode = cmd.mode
, hooksToRun = cmd.hooksToRun
, fileTarget = cmd.fileTarget
, format = fromMaybe config.global.format cmd.format
, stash = cmd.stash
}
{----- hooky fix ------}
cmdFix :: CLICommandDef
cmdFix =
CLICommandDef
{ name = "fix"
, description = "Run hooks with autofixing enabled"
, cmdType = Proxy @Cmd_Fix
}
newtype Cmd_Fix = Cmd_Fix Cmd_Run
instance IsCLICommand Cmd_Fix where
cliCommandParse = update <$> cliCommandParse
where
update Cmd_Run{..} = Cmd_Fix Cmd_Run{mode = Mode_Fix, ..}
cliCommandRun = coerce $ cliCommandRun @Cmd_Run
{----- hooky lint ------}
cmdLint :: CLICommandDef
cmdLint =
CLICommandDef
{ name = "lint"
, description = "Run builtin hooky lint rules"
, cmdType = Proxy @Cmd_Lint
}
data Cmd_Lint = Cmd_Lint
{ fileTarget :: GitFileTarget
, autofix :: Bool
}
instance IsCLICommand Cmd_Lint where
cliCommandParse = do
fileTarget <- GitFile.FilesGiven <$> parseFilesCLI
autofix <-
Opt.switch . mconcat $
[ Opt.long "fix"
, Opt.help "Whether to fix issues"
]
pure Cmd_Lint{..}
cliCommandRun _ cmd git config = do
files <- resolveGitFiles git cmd.fileTarget
report <-
runLintRules git config $
LintOptions
{ autofix = cmd.autofix
, files
}
Text.putStrLn $ renderLintReport report
unless (lintReportSuccess report) $ do
exitFailure
{----- CLI Helpers -----}
-- https://github.com/pcapriotti/optparse-applicative/issues/513
cliOneOfOptional :: [Opt.Parser a] -> Opt.Parser (Maybe a)
cliOneOfOptional parsers = validate <$> traverse Opt.optional parsers
where
validate results =
case catMaybes results of
[] -> Nothing
[a] -> Just a
_ -> abortImpure $ "Expected exactly one of: " <> (Text.intercalate ", " . map Text.pack) optNames
optNames = concatMap getOptNames parsers
getOptNames :: Opt.Parser x -> [String]
getOptNames = \case
Opt.Internal.NilP _ -> []
Opt.Internal.OptP opt -> [getOptName opt]
Opt.Internal.MultP p1 p2 -> getOptNames p1 <> getOptNames p2
Opt.Internal.AltP p1 p2 -> getOptNames p1 <> getOptNames p2
Opt.Internal.BindP p _ -> getOptNames p
getOptName opt =
case Opt.Internal.optMain opt of
Opt.Internal.OptReader names _ _ | Just name <- getName names -> name
Opt.Internal.FlagReader names _ | Just name <- getName names -> name
_ -> Opt.Internal.propMetaVar $ Opt.Internal.optProps opt
getName names
| n : _ <- [n | Opt.Internal.OptLong n <- names] = Just ("--" <> n)
| c : _ <- [c | Opt.Internal.OptShort c <- names] = Just ['-', c]
| otherwise = Nothing
parseFilesCLI :: Opt.Parser [GitFileTargetArg]
parseFilesCLI =
Opt.some . Opt.argument (parseGitFileTargetArg <$> Opt.str) . mconcat $
[ Opt.metavar "FILES"
, Opt.help . concat $
[ "Files to run on. If a directory is specified, recursively finds all files."
, "If `@path/to/f.ext` is specified, all files in `path/to/f.ext` will be used."
]
]
parseRunModeCLI :: Opt.Parser (Maybe RunMode)
parseRunModeCLI =
Opt.optional . Opt.option (Opt.maybeReader (parseRunMode . Text.pack)) . mconcat $
[ Opt.long "mode"
, Opt.help . Text.unpack $ "Mode to run hooky in during git hooks. One of: " <> modes
]
where
modes = Text.intercalate ", " $ map renderRunMode allRunModes
parseFormatCLI :: Opt.Parser (Maybe OutputFormat)
parseFormatCLI =
Opt.optional . Opt.option (Opt.maybeReader (parseOutputFormat . Text.pack)) . mconcat $
[ Opt.long "format"
, Opt.help . Text.unpack $ "Format of output. One of: " <> formats
]
where
formats = Text.intercalate ", " $ map renderOutputFormat allOutputFormats