hooky 1.0.9 → 1.0.10
raw patch · 13 files changed
+375/−88 lines, 13 filesdep +data-default
Dependencies added: data-default
Files
- CHANGELOG.md +6/−0
- README.md +16/−5
- hooky.cabal +6/−1
- src/Hooky/Config.hs +38/−10
- src/Hooky/Run.hs +3/−1
- src/Hooky/Utils/CSI.hs +123/−0
- src/Main.hs +63/−28
- test/Hooky/ConfigSpec.hs +7/−31
- test/Hooky/E2ESpec.hs +21/−9
- test/Hooky/LintSpec.hs +2/−3
- test/Hooky/RunSpec.hs +54/−0
- test/Hooky/TestUtils/Config.hs +35/−0
- test/Hooky/TestUtils/Git.hs +1/−0
CHANGELOG.md view
@@ -1,3 +1,9 @@+# v1.0.10++* Add `hooky uninstall`+* Fix installing hooky in worktrees+* Strip escape characters in hook output+ # v1.0.9 * Support specifying files as a list:
README.md view
@@ -10,7 +10,7 @@ * Show stdout while hook is in-progress * Support for passing files to hooks via response files -<img src="https://raw.githubusercontent.com/brandonchinn178/hooky/v1.0.9/scripts/demo/demo.gif" />+<img src="https://raw.githubusercontent.com/brandonchinn178/hooky/v1.0.10/scripts/demo/demo.gif" /> ## Installation @@ -32,7 +32,7 @@ ## Usage -* `hooky install [--mode MODE] [--format FORMAT]`+* `hooky install [--mode MODE] [--format FORMAT] [--absolute]` * Registers `hooky` with git hooks. * `--mode` determines what to do when hooks modify files: * `check` (default) - Run the commands in `check` mode, which shouldn't modify files@@ -42,8 +42,12 @@ * `minimal` (default) - Only show full stdout of failed hooks. * `full` - Show passed/skipped hooks, without their stdout. Include durations for all hooks. * `verbose` - Show full stdout + duration of all hooks.+ * `--absolute`: By default, the hook looks for any `hooky` executable on PATH; this option will instead save the absolute path to this `hooky` executable * Configure defaults with the [Global configuration](#global-configuration) +* `hooky uninstall`+ * Unregisters `hooky` from git hooks.+ * `hooky run [FILES ...] [-k HOOK]` * Manually runs the given hooks in `check` mode * Files may be specified as `@foo.txt`, where `foo.txt` contains one file per line.@@ -165,7 +169,7 @@ Available rules and rule-specific configuration: -* `check_broken_symlinks` - Check if any symlinks which do not point to anything+* `check_broken_symlinks` - Check if there are any symlinks which do not point to anything * `check_case_conflict` - Check if any files differ only by case, which would cause issues on case-insensitive filesystems like macOS * `check_merge_conflict` - Check if any files contain merge conflict strings * `end_of_file_fixer` - Ensure files end with exactly one newline@@ -181,11 +185,18 @@ ```kdl flags {- // The default --mode to use when committing, if not overridden in `hooky install`+ // The default --mode to use when committing, if not overridden in+ // `hooky install` --mode check - // The default --format to use when committing, if not overridden in `hooky install`+ // The default --format to use when committing, if not overridden in+ // `hooky install` --format minimal++ // When set, save the absolute path to hooky in the git pre-commit hook in+ // `hooky install`; otherwise, the git pre-commit hook will look for any+ // `hooky` executable on PATH.+ --absolute } // The maximum number of output lines to show while a hook is running
hooky.cabal view
@@ -1,7 +1,7 @@ cabal-version: 3.0 name: hooky-version: 1.0.9+version: 1.0.10 synopsis: A minimal git hooks manager description: A minimal git hooks manager. homepage: https://github.com/brandonchinn178/hooky#readme@@ -33,6 +33,7 @@ Hooky.Internal.Messages Hooky.Internal.Output Hooky.Internal.Temp+ Hooky.Utils.CSI Hooky.Utils.Git Hooky.Utils.Glob Hooky.Utils.OsPath@@ -45,6 +46,7 @@ , bytestring , concurrent-output , containers+ , data-default , deepseq , directory , file-io@@ -96,13 +98,16 @@ Hooky.ConfigSpec Hooky.E2ESpec Hooky.LintSpec+ Hooky.RunSpec Hooky.Utils.GlobSpec -- Test utilities+ Hooky.TestUtils.Config Hooky.TestUtils.Git Hooky.TestUtils.Hooky build-depends: base , containers+ , data-default , directory , filepath , hooky
src/Hooky/Config.hs view
@@ -35,6 +35,7 @@ import Control.Arrow (returnA) import Control.Monad (unless) import Data.Bifunctor qualified as Bifunctor+import Data.Default (Default (..)) import Data.List.NonEmpty (NonEmpty) import Data.List.NonEmpty qualified as NonEmpty import Data.Map qualified as Map@@ -56,13 +57,20 @@ import System.OsPath (OsPath, osp, (</>)) data Config = Config- { repoConfigPath :: OsPath- , repo :: RepoConfig+ { repo :: RepoConfig , global :: GlobalConfig , skippedHooks :: Set Text } deriving (Show, Eq) +instance Default Config where+ def =+ Config+ { repo = def+ , global = def+ , skippedHooks = def+ }+ loadConfig :: OsPath -> IO Config loadConfig repoConfigPath = do global <- loadGlobalConfig@@ -82,6 +90,14 @@ } deriving (Show, Eq) +instance Default RepoConfig where+ def =+ RepoConfig+ { fileGlobs = def+ , hooks = def+ , lintRules = def+ }+ loadRepoConfig :: OsPath -> IO RepoConfig loadRepoConfig path = do configFileExists <- doesFileExist path@@ -95,16 +111,17 @@ parseRepoConfig :: Text -> Either Text RepoConfig parseRepoConfig = Bifunctor.first KDL.renderDecodeError . KDL.decodeWith decoder where+ defaults = def @RepoConfig decoder = KDL.document $ proc () -> do mDefaults <- KDL.optional . KDL.nodeWith "defaults" $ KDL.children defaultsDecoder -< ()- let fileGlobs = getDefault [] mDefaults $ \(x) -> x+ let fileGlobs = getDefault defaults.fileGlobs mDefaults $ \(x) -> x hooks <- KDL.many $ KDL.node "hook" -< () lintRules <- KDL.dashNodesAt "lint_rules" -< () returnA -< RepoConfig{..} defaultsDecoder = proc () -> do fileGlobs <- KDL.optional $ filesDecoder -< () returnA -< (fileGlobs)- getDefault def mFlags f = fromMaybe def $ mFlags >>= f+ getDefault x mFlags f = fromMaybe x $ mFlags >>= f data HookConfig = HookConfig { name :: Text@@ -141,6 +158,16 @@ } deriving (Show, Eq) +instance Default GlobalConfig where+ def =+ GlobalConfig+ { mode = Mode_Check+ , format = Format_Minimal+ , useAbsolute = False+ , maxOutputLines = 5+ , maxParallelHooks = 5+ }+ loadGlobalConfig :: IO GlobalConfig loadGlobalConfig = do useGlobal <- not . maybe False (== "1") <$> lookupEnv "HOOKY_NO_GLOBAL"@@ -157,20 +184,21 @@ parseGlobalConfig :: Text -> Either Text GlobalConfig parseGlobalConfig = Bifunctor.first KDL.renderDecodeError . KDL.decodeWith decoder where+ defaults = def @GlobalConfig decoder = KDL.document $ proc () -> do mFlags <- KDL.optional . KDL.nodeWith "flags" $ KDL.children flagsDecoder -< ()- let mode = getFlag Mode_Check mFlags $ \(x, _, _) -> x- let format = getFlag Format_Minimal mFlags $ \(_, x, _) -> x- let useAbsolute = getFlag False mFlags $ \(_, _, x) -> x- maxOutputLines <- KDL.option 5 $ KDL.argAt "max_output_lines" -< ()- maxParallelHooks <- KDL.option 5 $ KDL.argAt "max_parallel_hooks" -< ()+ let mode = getFlag defaults.mode mFlags $ \(x, _, _) -> x+ let format = getFlag defaults.format mFlags $ \(_, x, _) -> x+ let useAbsolute = getFlag defaults.useAbsolute mFlags $ \(_, _, x) -> x+ maxOutputLines <- KDL.option defaults.maxOutputLines $ KDL.argAt "max_output_lines" -< ()+ maxParallelHooks <- KDL.option defaults.maxParallelHooks $ KDL.argAt "max_parallel_hooks" -< () returnA -< GlobalConfig{..} flagsDecoder = proc () -> do mode <- KDL.optional $ KDL.argAt "--mode" -< () format <- KDL.optional $ KDL.argAt "--format" -< () useAbsolute <- KDL.optional . KDL.nodeWith "--absolute" $ pure True -< () returnA -< (mode, format, useAbsolute)- getFlag def mFlags f = fromMaybe def $ mFlags >>= f+ getFlag x mFlags f = fromMaybe x $ mFlags >>= f {----- RunMode -----}
src/Hooky/Run.hs view
@@ -51,6 +51,7 @@ renderHookReport, ) import Hooky.Internal.Temp (hookyTmpDir)+import Hooky.Utils.CSI qualified as CSI import Hooky.Utils.Git (GitClient) import Hooky.Utils.Glob (matchesGlobs) import Hooky.Utils.OsPath qualified as OsPath@@ -366,7 +367,8 @@ initHookOutput :: Int -> ([LazyText] -> IO ()) -> IO HookOutput initHookOutput maxOutputLines renderBuf = do outputRef <- newIORef ([], Seq.empty)- let onLine line = do+ let onLine lineRaw = do+ let line = CSI.stripWith CSI.keepColor lineRaw progressLines <- atomicModifyIORef outputRef $ \(prev, buf) -> let buf' = (if Seq.length buf == maxOutputLines then Seq.drop 1 buf else buf) Seq.|> line
+ src/Hooky/Utils/CSI.hs view
@@ -0,0 +1,123 @@+{-# LANGUAGE OverloadedRecordDot #-}+{-# LANGUAGE OverloadedStrings #-}+{-# LANGUAGE NoFieldSelectors #-}++module Hooky.Utils.CSI (+ strip,+ stripWith,++ -- * Options+ StripOpts (..),+ keepColor,+) where++import Control.Applicative ((<|>))+import Data.Char (chr)+import Data.Foldable1 qualified as Foldable1+import Data.Function (on)+import Data.List.NonEmpty qualified as NonEmpty+import Data.Maybe (fromMaybe, mapMaybe)+import Data.String (IsString)+import Data.Text (Text)+import Data.Text qualified as Text+import Data.Text.Lazy (LazyText)+import Data.Text.Lazy qualified as LazyText+import GHC.Records (HasField (..))++data StripOpts = StripOpts+ { mKeepColor :: Maybe Bool+ }++instance Semigroup StripOpts where+ opts1 <> opts2 =+ StripOpts+ { mKeepColor = opts1.mKeepColor <|> opts2.mKeepColor+ }+instance Monoid StripOpts where+ mempty =+ StripOpts+ { mKeepColor = Nothing+ }++instance HasField "keepColor" StripOpts Bool where+ getField opts = fromMaybe False opts.mKeepColor++keepColor :: StripOpts+keepColor = mempty{mKeepColor = Just True}++strip :: (TextLike s) => s -> s+strip = stripWith mempty+{-# INLINE strip #-}++stripWith :: (TextLike s) => StripOpts -> s -> s+stripWith opts s0 =+ -- In the happy path, s0 has no control characters; do a quick check+ -- to avoid overhead+ if not $ any (\d -> contains d s0) ['\ESC', '\x9B', '\r']+ then s0+ -- Convert to/from LazyText so that the implementation+ -- only needs to use lazy text, and so that concatenations+ -- are performant+ else textFromLazy . go0 . textToLazy $ s0+ where+ go0 s =+ case breakOnOneOf ["\ESC[", "\x9B", "\r"] s of+ Nothing -> s+ -- "\r" is technically not a CSI command, but it's similar and we want to+ -- strip it too.+ Just (pre, "\r", post) -> pre <> go0 post+ Just (pre, delim, post) -> pre <> go1 delim post+ go1 buf s =+ case LazyText.span (inRange 0x30 0x3F) s of+ (params, s') -> go2 (buf <> params) s'+ go2 buf s =+ case LazyText.span (inRange 0x20 0x2F) s of+ (params, s') -> go3 (buf <> params) s'+ go3 buf s =+ case LazyText.uncons s of+ Just (c, s')+ | inRange 0x40 0x7E c ->+ let shouldStrip =+ case c of+ 'm' | opts.keepColor -> False+ _ -> True+ in if shouldStrip+ then go0 s'+ else buf <> LazyText.singleton c <> go0 s'+ -- Invalid CSI; always strip+ _ -> go0 s++ -- Quickly check if character is in Text; uses memchr+ contains c s =+ case textBreakOn (textSingleton c) s of+ (_, "") -> False+ _ -> True++ inRange lo hi c = chr lo <= c && c <= chr hi++ breakOnOneOf delims s =+ fmap (Foldable1.minimumBy (compare `on` fst3))+ . NonEmpty.nonEmpty+ . mapMaybe (\d -> breakOn d s)+ $ delims+ breakOn delim s =+ let (pre, post) = LazyText.breakOn delim s+ in (pre,delim,) <$> LazyText.stripPrefix delim post+ fst3 (a, _, _) = a+{-# INLINE stripWith #-}++class (IsString s, Eq s) => TextLike s where+ textBreakOn :: s -> s -> (s, s)+ textSingleton :: Char -> s+ textFromLazy :: LazyText -> s+ textToLazy :: s -> LazyText+instance TextLike Text where+ textBreakOn = Text.breakOn+ textSingleton = Text.singleton+ textFromLazy = LazyText.toStrict+ textToLazy = LazyText.fromStrict+instance TextLike LazyText where+ textBreakOn = LazyText.breakOn+ textSingleton = LazyText.singleton+ textFromLazy = id+ textToLazy = id
src/Main.hs view
@@ -35,7 +35,7 @@ parseRunMode, renderRunMode, )-import Hooky.Error (abortImpure)+import Hooky.Error (abort, abortImpure) import Hooky.Internal.GitFile ( GitFileTarget, GitFileTargetArg,@@ -71,6 +71,7 @@ doesFileExist, getPermissions, makeAbsolute,+ removeFile, renameFile, setPermissions, )@@ -82,15 +83,23 @@ import System.OsPath (OsPath, addExtension, osp, (</>)) import UnliftIO.Exception (Exception (..), SomeException (..), handleJust) -{----- CLI Options -----}+{----- CLI -----} +data CLI = CLI+ { run :: CLIEnv -> IO ()+ , options :: CLIOptions+ }+ data CLIOptions = CLIOptions- { run :: CLICommandAction- , configFile :: Maybe OsPath+ { configFile :: Maybe OsPath , verbose :: Bool } -type CLICommandAction = GitClient -> Config -> IO ()+data CLIEnv = CLIEnv+ { options :: CLIOptions+ , git :: GitClient+ , config :: Config+ } data CLICommandDef = forall cmd.@@ -103,10 +112,10 @@ class IsCLICommand cmd where cliCommandParse :: Opt.Parser cmd- cliCommandRun :: Proxy cmd -> cmd -> CLICommandAction+ cliCommandRun :: Proxy cmd -> cmd -> CLIEnv -> IO () -loadCLIOptions :: IO CLIOptions-loadCLIOptions =+loadCLI :: IO CLI+loadCLI = Opt.customExecParser prefs $ Opt.info (parseOptions <**> Opt.helper <**> version) . mconcat $ [ Opt.fullDesc@@ -136,7 +145,7 @@ , Opt.short 'v' , Opt.help "Increase logging verbosity" ]- pure CLIOptions{..}+ pure CLI{run, options = CLIOptions{..}} parseInternalCommand = Opt.subparser . (Opt.internal <>) . mconcat . map mkCommand $@@ -145,6 +154,7 @@ parseCommand = Opt.hsubparser . mconcat . map mkCommand $ [ cmdInstall+ , cmdUninstall , cmdRun , cmdFix , cmdLint@@ -162,21 +172,21 @@ IO.hSetEncoding IO.stdout IO.utf8 IO.hSetEncoding IO.stderr IO.utf8 - cli <- loadCLIOptions+ cli <- loadCLI Logging.initialize $- if cli.verbose+ if cli.options.verbose then Logging.LogLevel_Debug else Logging.LogLevel_Warn git <- initGitClient repoConfigPath <-- case cli.configFile of+ case cli.options.configFile of Nothing -> pure $ git.repo </> [osp|.hooky.kdl|] Just fp -> makeAbsolute fp config <- loadConfig repoConfigPath - cli.run git config+ cli.run CLIEnv{options = cli.options, git, config} handleErrors :: IO a -> IO a handleErrors = handleJust shouldHandle $ \(SomeException e) -> do@@ -217,17 +227,16 @@ , 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|]+ cliCommandRun _ cmd env = do+ hookFile <- env.git.getPath [osp|hooks/pre-commit|] backupOldHookFile hookFile - let useAbsolute = config.global.useAbsolute || cmd.useAbsolute+ let useAbsolute = env.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"@@ -238,7 +247,9 @@ , "fi" , Text.unwords . concat $ [ ["exec \"$hooky_exe\" __git"]- , ["--config", quote configPath]+ , case env.options.configFile of+ Just configPath -> ["--config", quote $ OsPath.toText configPath]+ Nothing -> [] , case cmd.mode of Just mode -> ["--mode", quote $ renderRunMode mode] Nothing -> []@@ -267,6 +278,30 @@ , "Backed up to: " <> OsPath.toLazyText backup ] +{----- hooky uninstall -----}++cmdUninstall :: CLICommandDef+cmdUninstall =+ CLICommandDef+ { name = "uninstall"+ , description = "Uninstall hooky as the git pre-commit hook"+ , cmdType = Proxy @Cmd_Uninstall+ }++data Cmd_Uninstall = Cmd_Uninstall++instance IsCLICommand Cmd_Uninstall where+ cliCommandParse = pure Cmd_Uninstall+ cliCommandRun _ _ env = do+ hookFile <- env.git.getPath [osp|hooks/pre-commit|]++ exists <- doesFileExist hookFile+ unless exists $ do+ abort "Hooky was not installed"++ removeFile hookFile+ LazyText.putStrLn $ Term.green "🧹 Hooky uninstalled"+ {----- hooky __git -----} cmdRunGit :: CLICommandDef@@ -287,13 +322,13 @@ mode <- parseRunModeCLI format <- parseFormatCLI pure Cmd_RunGit{..}- cliCommandRun _ cmd git config = do- runHooks git config $+ cliCommandRun _ cmd env = do+ runHooks env.git env.config $ RunOptions- { mode = fromMaybe config.global.mode cmd.mode+ { mode = fromMaybe env.config.global.mode cmd.mode , hooksToRun = Nothing , fileTarget = GitFile.FilesStaged- , format = fromMaybe config.global.format cmd.format+ , format = fromMaybe env.config.global.format cmd.format , stash = True } @@ -362,13 +397,13 @@ Just ft -> (ft, stashFlag) in Cmd_Run{mode = Mode_Check, ..} - cliCommandRun _ cmd git config = do- runHooks git config $+ cliCommandRun _ cmd env = do+ runHooks env.git env.config $ RunOptions { mode = cmd.mode , hooksToRun = cmd.hooksToRun , fileTarget = cmd.fileTarget- , format = fromMaybe config.global.format cmd.format+ , format = fromMaybe env.config.global.format cmd.format , stash = cmd.stash } @@ -415,10 +450,10 @@ ] pure Cmd_Lint{..} - cliCommandRun _ cmd git config = do- files <- resolveGitFiles git cmd.fileTarget+ cliCommandRun _ cmd env = do+ files <- resolveGitFiles env.git cmd.fileTarget report <-- runLintRules git config $+ runLintRules env.git env.config $ LintOptions { autofix = cmd.autofix , files
test/Hooky/ConfigSpec.hs view
@@ -3,16 +3,11 @@ module Hooky.ConfigSpec (spec) where -import Data.List.NonEmpty qualified as NonEmpty-import Data.Text (Text)-import Hooky.Config (- HookConfig (HookConfig),- PassFilesMode (..),- RepoConfig (RepoConfig),- parseRepoConfig,- )+import Data.Default (def)+import Hooky.Config (parseRepoConfig) import Hooky.Config qualified as HookConfig (HookConfig (..)) import Hooky.Config qualified as RepoConfig (RepoConfig (..))+import Hooky.TestUtils.Config (toHookConfig) import Hooky.Utils.Glob (toGlob) import Skeletest import Skeletest.Predicate qualified as P@@ -35,7 +30,7 @@ } """ expected =- emptyRepoConfig+ def { RepoConfig.fileGlobs = [toGlob "*.hs", toGlob "*.md"] } parseRepoConfig input `shouldBe` Right expected@@ -51,7 +46,7 @@ } """ expected =- emptyRepoConfig+ def { RepoConfig.fileGlobs = [toGlob "*.hs", toGlob "*.md"] } parseRepoConfig input `shouldBe` Right expected@@ -69,7 +64,7 @@ } """ expected =- emptyRepoConfig+ def { RepoConfig.hooks = [ (toHookConfig "myHook" ["foo"]) { HookConfig.fileGlobs = [toGlob "*.hs", toGlob "*.md"]@@ -90,7 +85,7 @@ } """ expected =- emptyRepoConfig+ def { RepoConfig.hooks = [ (toHookConfig "myHook" ["foo"]) { HookConfig.fileGlobs = [toGlob "*.hs", toGlob "*.md"]@@ -133,22 +128,3 @@ it "fails if 'files' specified" $ do parseRepoConfig ("lint_rules { - " <> rule <> " { files *.txt; }; }") `shouldSatisfy` P.left (P.hasInfix "'files' config is not supported for")--emptyRepoConfig :: RepoConfig-emptyRepoConfig =- RepoConfig- { fileGlobs = []- , hooks = []- , lintRules = []- }--toHookConfig :: Text -> [Text] -> HookConfig-toHookConfig name args =- HookConfig- { name- , cmdArgs = NonEmpty.fromList args- , checkArgs = []- , fixArgs = []- , passFiles = PassFiles_XArgs- , fileGlobs = []- }
test/Hooky/E2ESpec.hs view
@@ -1,6 +1,7 @@ {-# LANGUAGE MultilineStrings #-} {-# LANGUAGE OverloadedRecordDot #-} {-# LANGUAGE OverloadedStrings #-}+{-# LANGUAGE QuasiQuotes #-} module Hooky.E2ESpec (spec) where @@ -9,8 +10,9 @@ import Data.Text qualified as Text import Data.Text.IO qualified as Text import Hooky.Internal.Output (allOutputFormats, renderOutputFormat)-import Hooky.TestUtils.Git (TestGitClient, withGitRepo)+import Hooky.TestUtils.Git (TestGitClient (..), withGitRepo) import Hooky.TestUtils.Hooky (HookyExe (..))+import Hooky.Utils.CSI qualified as CSI import Skeletest import Skeletest.Predicate qualified as P import System.Directory (@@ -21,8 +23,9 @@ renameFile, ) import System.Exit (ExitCode (..))-import System.FilePath ((</>))+import System.FilePath qualified as FilePath import System.IO qualified as IO+import System.OsPath (osp, (</>)) import System.Process qualified as Process import System.Timeout (timeout) @@ -47,6 +50,20 @@ stderr1 `shouldSatisfy` P.hasInfix "1 hook passed" stderr1 `shouldNotSatisfy` P.hasInfix "[warn]" + it "uses the hooky config in the worktree" . withGitRepo $ \git -> do+ writeFile ".hooky.kdl" ""+ runHooky ["install"] `shouldSatisfy` P.returns (P.eq ExitSuccess)+ git.exec ["add", "."] *> git.exec ["commit", "-m", "initial"]++ git.exec ["worktree", "add", "./worktree"]+ let git2 = TestGitClient{repo = git.repo </> [osp|worktree|]}+ writeFile "./worktree/.hooky.kdl" hookyConfigEofFixer+ writeFile "./worktree/bad.txt" "bad"+ git2.exec ["add", "."]+ (code, _, stderr) <- git2.run ["commit", "-m", "commit"]+ code `shouldBe` ExitFailure 1+ stderr `shouldSatisfy` P.hasInfix "1 hook failed"+ describe "hooky run" $ do it "defaults to --stash --staged" $ do withGitRepo $ \git -> do@@ -307,7 +324,7 @@ createDirectory dir forM_ [1 .. 100 :: Int] $ \y -> do let file = Text.unpack $ Text.replicate 100 "b" <> Text.show y- writeFile (dir </> file) ""+ writeFile (dir FilePath.</> file) "" git.exec ["add", "."] git.exec ["commit", "-m", "test", "-q"] @@ -328,12 +345,7 @@ let (stdout, stderr) = (Text.pack stdoutS, Text.pack stderrS) Text.hPutStrLn IO.stdout stdout Text.hPutStrLn IO.stderr stderr- pure (code, stripControlChars stdout, stripControlChars stderr)- where- stripControlChars s =- case Text.breakOn "\x1b" s of- (_, "") -> s- (pre, post) -> pre <> stripControlChars (Text.drop 1 . Text.dropWhile (/= 'm') $ post)+ pure (code, CSI.strip stdout, CSI.strip stderr) commitHookyEofFixer :: TestGitClient -> IO () commitHookyEofFixer git = do
test/Hooky/LintSpec.hs view
@@ -34,7 +34,7 @@ removeFile, ) import System.FilePath ((</>))-import System.OsPath (OsPath, osp)+import System.OsPath (OsPath) import System.Timeout (timeout) import UnliftIO.Exception (SomeException) @@ -404,8 +404,7 @@ defaultConfig :: LintRuleRule -> Config defaultConfig rule = Config- { repoConfigPath = [osp|.hooky.kdl|]- , repo =+ { repo = RepoConfig { fileGlobs = [] , hooks = []
+ test/Hooky/RunSpec.hs view
@@ -0,0 +1,54 @@+{-# LANGUAGE OverloadedRecordDot #-}+{-# LANGUAGE OverloadedStrings #-}+{-# LANGUAGE QuasiQuotes #-}++module Hooky.RunSpec (spec) where++import Data.Default (def)+import Hooky.Config (RunMode (..))+import Hooky.Config qualified as RepoConfig (RepoConfig (..))+import Hooky.Internal.GitFile (GitFileTarget (..), GitFileTargetArg (..))+import Hooky.Internal.Output (OutputFormat (..))+import Hooky.Run (RunOptions (..), runHooks)+import Hooky.TestUtils.Config (toConfig, toHookConfig)+import Hooky.TestUtils.Git (withGitRepo)+import Skeletest+import Skeletest.Predicate qualified as P+import System.OsPath (osp)++spec :: Spec+spec = do+ describe "runHooks" $ do+ it "strips control characters except color" $ do+ withGitRepo $ \git -> do+ let config =+ toConfig+ def+ { RepoConfig.hooks =+ [ toHookConfig "colorful" $+ [ "bash"+ , "-c"+ , "printf '\\e[31mThis is red\\e[0m'"+ ]+ , toHookConfig "clear-initial" $+ [ "bash"+ , "-c"+ , "printf 'Before\\r\\e[2KAfter'"+ ]+ ]+ }+ writeFile "README" ""+ runHooks git.client config runOptions+ stdout <- (.getStdout) =<< getFixture @FixtureCapturedOutput+ stdout `shouldSatisfy` P.hasInfix "│ \ESC[31mThis is red\ESC[0m"+ stdout `shouldSatisfy` P.hasInfix "│ BeforeAfter"++runOptions :: RunOptions+runOptions =+ RunOptions+ { mode = Mode_Check+ , hooksToRun = Nothing+ , fileTarget = FilesGiven [FileArg [osp|.|]]+ , format = Format_Verbose+ , stash = False+ }
+ test/Hooky/TestUtils/Config.hs view
@@ -0,0 +1,35 @@+{-# LANGUAGE OverloadedStrings #-}++module Hooky.TestUtils.Config (+ toConfig,+ toHookConfig,+) where++import Data.Default (def)+import Data.List.NonEmpty qualified as NonEmpty+import Data.Text (Text)+import Hooky.Config (Config, HookConfig (..), PassFilesMode (..), RepoConfig)+import Hooky.Config qualified as Config (Config (..))+import Hooky.Config qualified as GlobalConfig (GlobalConfig (..))+import Hooky.Utils.Glob (toGlob)++toConfig :: RepoConfig -> Config+toConfig repoConfig =+ def+ { Config.global =+ def+ { GlobalConfig.maxParallelHooks = 1+ }+ , Config.repo = repoConfig+ }++toHookConfig :: Text -> [Text] -> HookConfig+toHookConfig name args =+ HookConfig+ { name+ , cmdArgs = NonEmpty.fromList args+ , checkArgs = []+ , fixArgs = []+ , passFiles = PassFiles_XArgs+ , fileGlobs = [toGlob "*"]+ }
test/Hooky/TestUtils/Git.hs view
@@ -2,6 +2,7 @@ {-# LANGUAGE OverloadedRecordDot #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE QuasiQuotes #-}+{-# LANGUAGE NoFieldSelectors #-} module Hooky.TestUtils.Git ( TestGitClient (..),