hooky (empty) → 1.0.9
raw patch · 29 files changed
+4220/−0 lines, 29 filesdep +Globdep +ansi-terminaldep +base
Dependencies added: Glob, ansi-terminal, base, bytestring, concurrent-output, containers, deepseq, directory, file-io, filepath, hooky, kdl-hs, optparse-applicative, os-string, process, scientific, skeletest, temporary, text, time, unliftio
Files
- CHANGELOG.md +61/−0
- LICENSE.md +11/−0
- README.md +279/−0
- hooky.cabal +115/−0
- src/Hooky/Config.hs +311/−0
- src/Hooky/Error.hs +21/−0
- src/Hooky/Internal/GitFile.hs +255/−0
- src/Hooky/Internal/Logging.hs +97/−0
- src/Hooky/Internal/Messages.hs +26/−0
- src/Hooky/Internal/Output.hs +78/−0
- src/Hooky/Internal/Temp.hs +39/−0
- src/Hooky/Lint.hs +337/−0
- src/Hooky/Run.hs +408/−0
- src/Hooky/Utils/Git.hs +63/−0
- src/Hooky/Utils/Glob.hs +84/−0
- src/Hooky/Utils/OsPath.hs +82/−0
- src/Hooky/Utils/Process.hs +144/−0
- src/Hooky/Utils/Term.hs +63/−0
- src/Hooky/Utils/Text.hs +12/−0
- src/Main.hs +486/−0
- test/Hooky/ConfigSpec.hs +154/−0
- test/Hooky/E2ESpec.hs +355/−0
- test/Hooky/LintSpec.hs +427/−0
- test/Hooky/TestUtils/Git.hs +64/−0
- test/Hooky/TestUtils/Hooky.hs +18/−0
- test/Hooky/Utils/GlobSpec.hs +109/−0
- test/Hooky/__snapshots__/E2ESpec.snap.md +50/−0
- test/Hooky/__snapshots__/LintSpec.snap.md +70/−0
- test/Main.hs +1/−0
+ CHANGELOG.md view
@@ -0,0 +1,61 @@+# v1.0.9++* Support specifying files as a list:++ ```kdl+ files {+ - *.hs+ - *.txt+ }+ ```++# v1.0.8++* Output `--verbose` logs to stderr+* Log all subprocess calls+* Fix "Argument list too long" error in large repos+* Fix `check_broken_symlinks` failing when a symlink points to a directory that only has nested files+ * e.g. `foo-link -> foo/bar`, but only `foo/bar/a/b/c/baz.txt` exists+* Show all successful `hooky lint` linters+* Include hidden files/directories in `*` and `**` file globs++# v1.0.7++* Fix regression loading files with whitespace in name++# v1.0.6++* Fix regression running after `git mv`++# v1.0.5++* Support brace expansion in file globs ([#37](https://github.com/brandonchinn178/hooky/pull/37))+* Various symlink fixes ([#39](https://github.com/brandonchinn178/hooky/pull/39), [#40](https://github.com/brandonchinn178/hooky/pull/40), [#41](https://github.com/brandonchinn178/hooky/pull/41))+ * Fix errors when repo contains symlinks that point to a directory+ * Fix errors when repo contains symlinks in subdirectories with relative paths++# v1.0.4++* Filter out deleted files ([#32](https://github.com/brandonchinn178/hooky/pull/32))++# v1.0.3++* Force utf-8 encoding ([#23](https://github.com/brandonchinn178/hooky/issues/23))+* Fix stashing untracked renamed files ([#27](https://github.com/brandonchinn178/hooky/issues/27))+* Fix mangled output on long command ([#26](https://github.com/brandonchinn178/hooky/issues/26))++# v1.0.2++* Change `hooky install` to use any `hooky` on PATH, since absolute path may be version-specific and break on upgrade+* Add `--absolute` flag to `hooky install` to force using the absolute path to `hooky` in the pre-commit hook+* Improve performance of `check_case_conflict` lint rule+* Respect `files` config for lint rules++# v1.0.1++* Fix `end_of_file_fixer` failing on empty files+* Add extra newline in output, to improve the spacing++# v1.0.0++* Initial release
+ LICENSE.md view
@@ -0,0 +1,11 @@+Copyright © 2024-present Brandon Chinn++Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:++1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.++2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.++3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.++THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ README.md view
@@ -0,0 +1,279 @@+# Hooky++Minimal git hooks manager.++Features:+* Only runs on staged files+ * Supports partially staged and untracked files+* Hooks run in parallel+* Built-in support for auto-fixing files+* 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" />++## Installation++### With Homebrew++```shell+brew install brandonchinn178/tap/hooky+```++### With Nix++```shell+nix profile install nixpkgs#hooky+```++### GitHub release++Download the appropriate binary from the [GitHub releases page](https://github.com/brandonchinn178/hooky/releases).++## Usage++* `hooky install [--mode MODE] [--format FORMAT]`+ * 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+ * `fix` - Run the commands in `fix` mode, which may modify files+ * `fix-add` - Same as `fix`, except add the changes to the stage and continue the commit+ * `--format` determines how to format the output:+ * `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.+ * Configure defaults with the [Global configuration](#global-configuration)++* `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.+ * Shortcuts:+ * `--modified`/`-m` = `@<(git diff --name-only --diff-filter=AMR)`+ * `--staged`/`-s` = `@<(git diff --staged --name-only --diff-filter=AMR)`+ * `--all`/`-a` = `@<(git ls-files)`+ * `--prev`/`-1` = `@<(git diff HEAD~1..HEAD --name-only --diff-filter=AMR)`+ * `--stash` stashes all unstaged changes before running+ * If no files are specified, equivalent to `--stash --staged`+ * `-k` may be specified multiple times, specifying the hooks to run++* `hooky fix [FILES ...] [-k HOOK]`+ * Same as `hooky run`, except runs in `fix` mode++### `.hooky.kdl` configuration++Configuration is specified with the [KDL](https://kdl.dev) language.++Each hook is specified in a `hook` section:++```kdl+hook name_of_hook {+ command my_formatter arg0 arg1 {+ check_args --mode check+ fix_args --mode fix+ pass_files file+ }+ files *.py *.txt+}+```++* `command`: The command to run+ * You're responsible for installing the necessary tools. [dotslash](https://dotslash-cli.com/docs) is a good way to automatically install binary tools.+ * Can be written without quotes, but quotes are needed if special characters like `/` or spaces are used+* `check_args`: Additional arguments to pass when running in `check` mode+* `fix_args`: Additional arguments to pass when running in `fix` mode+* `pass_files`: How to pass files to the command+ * `xargs` (default) - Pass files to `xargs`, which will batch execute+ * `xargs_parallel` - Same as `xargs`, except run in parallel+ * `file` - Put files into a file (one file per line) and pass the list as an argument as `@path/to/file.txt`+ * `none` - Don't pass files to the command at all+* `files`: Globs of files that should trigger the hook+ * See [File globs](#file-globs) for supported syntax+ * Globs may be specified as arguments or lists:+ ```kdl+ files *.hs *.txt++ files {+ - *.hs+ - *.txt+ }+ ```+ * When multiple globs are specified, a file matches if:+ * Any positive globs match, AND+ * All negative globs don't match++You may also specify defaults in the `defaults` section. Available options are documented below:++```kdl+defaults {+ // Any globs specified here are inherited by all hooks+ files *.py+}+```++### File globs++File globs are represented as KDL strings supporting the following syntax:++* `*` matches any character except `/`+* `**` matches zero or more directories+ * e.g. `a/**/*.txt` matches `a/foo.txt` and `a/b/foo.txt` but not `b/foo.txt`+* Relative paths match anywhere in the repo+ * e.g. `*.txt` matches `foo.txt` and `foo/bar.txt`+ * In other words, `**/` is auto-prepended to the beginning+* Absolute paths match from the root of the repo+ * e.g. `/*.txt` matches `foo.txt` but not `foo/bar.txt`+* A glob can be negated with a `!` at the beginning+ * e.g. `!foo.txt` matches `bar.txt` but not `foo.txt` nor `a/foo.txt`+ * e.g. `!/foo.txt` matches `bar.txt` and `a/foo.txt` but not `foo.txt`++Per normal KDL string syntax, it may be left unquoted if there are no special characters. Specifically, it can be unquoted for a simple `*.txt` glob, but any globs with `/` require quotes.++### Built-in hooks++For convenience, Hooky also ships with some general purpose hooks, which can be specified as:++```kdl+hook hooky {+ command hooky lint {+ fix_args --fix+ pass_files file+ }+ files *+}+```++`hooky lint` runs the rules specified under the `lint_rules` section, e.g.++```kdl+lint_rules {+ - check_broken_symlinks+ - no_commit_to_branch {+ branches {+ - main+ - release-*+ }+ }+ - trailing_whitespace {+ files "!foo.txt"+ }+}+```++All rules have the following configuration:++* `files`: Same as `files` in `hook` sections. If not specified, defaults to `*`++Available rules and rule-specific configuration:++* `check_broken_symlinks` - Check if 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+* `no_commit_to_branch` - Prevent commits to specific branches+ * `branches` - Branches to prevent commits to, as a glob pattern+* `trailing_whitespace` - Remove trailing whitespace++### Global configuration++Global configuration can also be specified at `$XDG_CONFIG_DIR/hooky/settings.kdl` (e.g. `~/.config/hooky/settings.kdl`).++Available configuration and their defaults is documented below:++```kdl+flags {+ // 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`+ --format minimal+}++// The maximum number of output lines to show while a hook is running+max_output_lines 5++// The maximum number of hooks to run in parallel in `check` mode+max_parallel_hooks 5+```++### Skipping hooks++To temporarily skip hooks, use the `SKIP` env var, which takes a comma-delimited list of hooks to skip. This works for both `hook`s and `lint_rules`.++## Example hook configurations++### Ruff in a uv project++```kdl+hook ruff_check {+ command uv run ruff check {+ fix_args --fix+ pass_files file+ }+ files *.py+}++hook ruff_format {+ command uv run ruff format {+ check_args --check+ pass_files file+ }+ files *.py+}+```++### ESLint in an npm project++```kdl+hook eslint {+ command npx eslint {+ fix_args --fix+ pass_files xargs+ }+ files *.json *.js *.jsx *.ts *.tsx+}+```++### Uses of Hooky in the wild++See examples of Hooky configurations across GitHub: https://github.com/search?q=path%3A.hooky.kdl&type=code++## Comparison with other tools++### pre-commit++[`pre-commit`](https://pre-commit.com) is primarily a tool/environment manager ([ref](https://github.com/pre-commit/pre-commit/pull/3577), [ref2](https://github.com/pre-commit/pre-commit/issues/2316#issuecomment-1083643390)), not a command runner. IMO this is the wrong direction:+* `pre-commit` doesn't have any lockfiles, whereas your language's normal dependency management will likely support pinned dependencies+* With `pre-commit`, you have to re-configure the linter in `.pre-commit-config.yaml`, e.g. re-specifying `eslint` plugins++At the end of the day, git pre-commit hooks should just be a matter of taking commands you can already run manually and registering them with git hooks. That is the only thing Hooky cares about, and how you want to manage your tools is up to you.++Other notable differences:+* `hooky` installs as a compiled executable; no need to have the right Python environment+* Built-in functionality for fixing failures, with optional auto-add fixes in commit+* Hooks run in parallel+* Show hook output while it's running, to get more visibility into what's happening+* Support passing files via response files instead of using `xargs`++### husky++[Husky](https://typicode.github.io/husky/#/) is pretty specific to NodeJS projects. It's implemented in Javascript, so you need to install Husky with `npm`. By default, it will run the `prepare` script in `package.json`, but you can also add arbitrary commands to `.husky/pre-commit`. This is flexible, but completely open-ended, with no structure running/configuring each hook independently.++### prek++[prek](https://prek.j178.dev/) is essentially a reimplementation of [`pre-commit`](https://pre-commit.com), so it inherits the same issues.++### lefthook++[lefthook](https://lefthook.dev) has a similar philosophy as Hooky around only specifying commands to run.++The biggest difference between Hooky and lefthook is Hooky natively distinguishes between check and fix modes. You commit to the repo how a given linter checks and fixes, and each developer decides for themselves whether they want the git hook to only check without modification, or to also autofix. Hooky will fail to commit if anything is fixed (unless you run in the `fix-add` mode) and displays a message on adding the changes to your commit. Without `stage_fixed`, lefthook will simply leave the changes on disk and continue the commit.++In general, Hooky also aims to be much more minimal:+* lefthook always shows the output of the command that was run, whereas Hooky only shows the output for failed commands by default+* lefthook's configuration is much more complex. It also supports configuring general tasks, whereas Hooky focuses only on managing git hook commands. Your project probably already has general task runners like `Makefile` or `pyproject.toml`/`package.json` scripts.++Other notable differences:+* Hooky comes with some useful linters out-of-the-box like checking trailing whitespace, for convenience.+* Hooky stashes partially staged changes, which ensures that when a linter runs on a file, it will see exactly the content that's going into the commit and not lint unstaged changes.+* Hooky shows the output of a linter while it's running, so users have visibility into what's taking a long time. lefthook only shows output at the end.+* Hooky supports passing the modified files to the command as a response file (`@files.txt`), so that a long list of files still only invokes the command once, and the command can read all the files from there (if it supports it).
+ hooky.cabal view
@@ -0,0 +1,115 @@+cabal-version: 3.0++name: hooky+version: 1.0.9+synopsis: A minimal git hooks manager+description: A minimal git hooks manager.+homepage: https://github.com/brandonchinn178/hooky#readme+bug-reports: https://github.com/brandonchinn178/hooky/issues+author: Brandon Chinn <brandonchinn178@gmail.com>+maintainer: Brandon Chinn <brandonchinn178@gmail.com>+license: BSD-3-Clause+license-file: LICENSE.md+category: Tools+build-type: Simple+extra-source-files:+ README.md+ CHANGELOG.md+ test/**/*.snap.md++source-repository head+ type: git+ location: https://github.com/brandonchinn178/hooky++library+ hs-source-dirs: src+ exposed-modules:+ Hooky.Config+ Hooky.Error+ Hooky.Lint+ Hooky.Run+ Hooky.Internal.GitFile+ Hooky.Internal.Logging+ Hooky.Internal.Messages+ Hooky.Internal.Output+ Hooky.Internal.Temp+ Hooky.Utils.Git+ Hooky.Utils.Glob+ Hooky.Utils.OsPath+ Hooky.Utils.Process+ Hooky.Utils.Term+ Hooky.Utils.Text+ build-depends:+ base < 5+ , ansi-terminal+ , bytestring+ , concurrent-output+ , containers+ , deepseq+ , directory+ , file-io+ , filepath+ , Glob+ , kdl-hs >= 1.1.0+ , os-string+ , process+ , scientific+ , text+ , time+ , unliftio+ default-language: GHC2024+ ghc-options: -Wall -Wcompat++executable hooky+ main-is: src/Main.hs+ other-modules:+ Paths_hooky+ autogen-modules:+ Paths_hooky+ build-depends:+ base+ , containers+ , directory+ , file-io+ , filepath+ , hooky+ , optparse-applicative+ , process+ , text+ , unliftio+ default-language: GHC2024+ ghc-options:+ -Wall -Wcompat+ -- https://github.com/commercialhaskell/stack/issues/3918+ -optP-Wno-nonportable-include-path+ -threaded++test-suite hooky-tests+ type: exitcode-stdio-1.0+ ghc-options: -F -pgmF=skeletest-preprocessor -threaded+ build-tool-depends:+ , skeletest:skeletest-preprocessor+ , hooky:hooky+ hs-source-dirs: test+ main-is: Main.hs+ other-modules:+ Hooky.ConfigSpec+ Hooky.E2ESpec+ Hooky.LintSpec+ Hooky.Utils.GlobSpec+ -- Test utilities+ Hooky.TestUtils.Git+ Hooky.TestUtils.Hooky+ build-depends:+ base+ , containers+ , directory+ , filepath+ , hooky+ , process+ , skeletest >= 0.3.0+ , temporary+ , text+ , unliftio+ default-language: GHC2024+ ghc-options: -Wall -Wcompat
+ src/Hooky/Config.hs view
@@ -0,0 +1,311 @@+{-# LANGUAGE Arrows #-}+{-# LANGUAGE DuplicateRecordFields #-}+{-# LANGUAGE LambdaCase #-}+{-# LANGUAGE OrPatterns #-}+{-# LANGUAGE OverloadedRecordDot #-}+{-# LANGUAGE OverloadedStrings #-}+{-# LANGUAGE QuasiQuotes #-}+{-# LANGUAGE RecordWildCards #-}+{-# LANGUAGE NoFieldSelectors #-}+{-# OPTIONS_GHC -Wno-orphans #-}++module Hooky.Config (+ -- * Config+ Config (..),+ loadConfig,+ parseRepoConfig,++ -- * RepoConfig+ RepoConfig (..),+ HookConfig (..),+ PassFilesMode (..),+ LintRule (..),+ LintRuleRule (..),++ -- * GlobalConfig+ GlobalConfig (..),++ -- ** RunMode+ RunMode (..),+ allRunModes,+ parseRunMode,+ renderRunMode,+) where++import Control.Arrow (returnA)+import Control.Monad (unless)+import Data.Bifunctor qualified as Bifunctor+import Data.List.NonEmpty (NonEmpty)+import Data.List.NonEmpty qualified as NonEmpty+import Data.Map qualified as Map+import Data.Maybe (fromMaybe)+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 GHC.Records (HasField (..))+import Hooky.Error (abort)+import Hooky.Internal.Output (OutputFormat (..), parseOutputFormat)+import Hooky.Utils.Glob (Glob, toGlob)+import Hooky.Utils.OsPath qualified as OsPath+import KDL.Arrow qualified as KDL+import System.Directory.OsPath (XdgDirectory (..), doesFileExist, getXdgDirectory)+import System.Environment (lookupEnv)+import System.File.OsPath qualified as OsPath+import System.OsPath (OsPath, osp, (</>))++data Config = Config+ { repoConfigPath :: OsPath+ , repo :: RepoConfig+ , global :: GlobalConfig+ , skippedHooks :: Set Text+ }+ deriving (Show, Eq)++loadConfig :: OsPath -> IO Config+loadConfig repoConfigPath = do+ global <- loadGlobalConfig+ repo <- loadRepoConfig repoConfigPath++ let fromCSV = Text.splitOn "," . Text.pack+ skippedHooks <- Set.fromList . maybe [] fromCSV <$> lookupEnv "SKIP"++ pure Config{..}++{----- RepoConfig -----}++data RepoConfig = RepoConfig+ { fileGlobs :: [Glob]+ , hooks :: [HookConfig]+ , lintRules :: [LintRule]+ }+ deriving (Show, Eq)++loadRepoConfig :: OsPath -> IO RepoConfig+loadRepoConfig path = do+ configFileExists <- doesFileExist path+ unless configFileExists $ do+ abort $ "Config file doesn't exist: " <> OsPath.toText path+ content <- Text.decodeUtf8 <$> OsPath.readFile' path+ case parseRepoConfig content of+ Right config -> pure config+ Left e -> abort $ "Could not parse config: " <> OsPath.toText path <> "\n" <> e++parseRepoConfig :: Text -> Either Text RepoConfig+parseRepoConfig = Bifunctor.first KDL.renderDecodeError . KDL.decodeWith decoder+ where+ decoder = KDL.document $ proc () -> do+ mDefaults <- KDL.optional . KDL.nodeWith "defaults" $ KDL.children defaultsDecoder -< ()+ let fileGlobs = getDefault [] 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++data HookConfig = HookConfig+ { name :: Text+ , cmdArgs :: NonEmpty Text+ , checkArgs :: [Text]+ , fixArgs :: [Text]+ , passFiles :: PassFilesMode+ , fileGlobs :: [Glob]+ }+ deriving (Show, Eq)++instance KDL.DecodeNode HookConfig where+ nodeDecoder = proc () -> do+ name <- KDL.arg -< ()+ finalize <- KDL.children $ KDL.nodeWith "command" $ commandDecoder -< ()+ fileGlobs <- KDL.children $ filesDecoder -< ()+ returnA -< finalize name fileGlobs+ where+ commandDecoder = proc () -> do+ cmdArgs <- NonEmpty.fromList <$> KDL.some KDL.arg -< ()+ checkArgs <- KDL.children $ KDL.argsAt "check_args" -< ()+ fixArgs <- KDL.children $ KDL.argsAt "fix_args" -< ()+ passFiles <- KDL.children $ KDL.option PassFiles_XArgs $ KDL.argAt "pass_files" -< ()+ returnA -< (\name fileGlobs -> HookConfig{..})++{----- GlobalConfig -----}++data GlobalConfig = GlobalConfig+ { mode :: RunMode+ , format :: OutputFormat+ , useAbsolute :: Bool+ , maxOutputLines :: Int+ , maxParallelHooks :: Int+ }+ deriving (Show, Eq)++loadGlobalConfig :: IO GlobalConfig+loadGlobalConfig = do+ useGlobal <- not . maybe False (== "1") <$> lookupEnv "HOOKY_NO_GLOBAL"++ hookyConfigDir <- getXdgDirectory XdgConfig [osp|hooky|]+ let path = hookyConfigDir </> [osp|settings.kdl|]+ exists <- doesFileExist path++ content <- if useGlobal && exists then Text.decodeUtf8 <$> OsPath.readFile' path else pure ""+ case parseGlobalConfig content of+ Right config -> pure config+ Left e -> abort $ "Could not parse config: " <> OsPath.toText path <> "\n" <> e++parseGlobalConfig :: Text -> Either Text GlobalConfig+parseGlobalConfig = Bifunctor.first KDL.renderDecodeError . KDL.decodeWith decoder+ where+ 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" -< ()+ 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++{----- RunMode -----}++data RunMode = Mode_Check | Mode_Fix | Mode_FixAdd+ deriving (Show, Eq, Enum, Bounded)++allRunModes :: [RunMode]+allRunModes = [minBound .. maxBound]++parseRunMode :: Text -> Maybe RunMode+parseRunMode = flip Map.lookup x+ where+ x = Map.fromList [(renderRunMode m, m) | m <- allRunModes]++renderRunMode :: RunMode -> Text+renderRunMode = \case+ Mode_Check -> "check"+ Mode_Fix -> "fix"+ Mode_FixAdd -> "fix-add"++instance KDL.DecodeValue RunMode where+ valueDecoder = KDL.withDecoder KDL.valueDecoder $ \s ->+ case parseRunMode s of+ Nothing -> KDL.failM $ "Invalid --mode: " <> s+ Just mode -> pure mode++{----- OutputFormat -----}++instance KDL.DecodeValue OutputFormat where+ valueDecoder = KDL.withDecoder KDL.valueDecoder $ \s ->+ case parseOutputFormat s of+ Nothing -> KDL.failM $ "Invalid --format: " <> s+ Just format -> pure format++{----- LintRule -----}++data LintRule = LintRule+ { rule :: LintRuleRule+ , fileGlobs :: [Glob]+ }+ deriving (Show, Eq)++data LintRuleRule+ = LintRule_CheckBrokenSymlinks+ | LintRule_CheckCaseConflict+ | LintRule_CheckMergeConflict+ | LintRule_EndOfFileFixer+ | LintRule_NoCommitToBranch [Glob]+ | LintRule_TrailingWhitespace+ deriving (Show, Eq)++instance HasField "name" LintRule Text where+ getField LintRule{rule} = rule.name+instance HasField "name" LintRuleRule Text where+ getField = \case+ -- Must match lintRuleDecoder+ LintRule_CheckBrokenSymlinks{} -> "check_broken_symlinks"+ LintRule_CheckCaseConflict{} -> "check_case_conflict"+ LintRule_CheckMergeConflict{} -> "check_merge_conflict"+ LintRule_EndOfFileFixer{} -> "end_of_file_fixer"+ LintRule_NoCommitToBranch{} -> "no_commit_to_branch"+ LintRule_TrailingWhitespace{} -> "trailing_whitespace"++instance KDL.DecodeNode LintRule where+ nodeDecoder = proc () -> do+ name <- KDL.arg -< ()+ rule <- ruleDecoder -< name+ fileGlobs <- filesDecoder' -< rule+ returnA -< LintRule{..}+ where+ ruleDecoder = proc name -> do+ case name of+ "check_broken_symlinks" ->+ returnA -< LintRule_CheckBrokenSymlinks+ "check_case_conflict" ->+ returnA -< LintRule_CheckCaseConflict+ "check_merge_conflict" ->+ returnA -< LintRule_CheckMergeConflict+ "end_of_file_fixer" ->+ returnA -< LintRule_EndOfFileFixer+ "no_commit_to_branch" -> do+ branchesRaw <- KDL.children $ KDL.dashChildrenAt "branches" -< ()+ let branches = if null branchesRaw then map toGlob ["main", "master"] else branchesRaw+ returnA -< LintRule_NoCommitToBranch branches+ "trailing_whitespace" ->+ returnA -< LintRule_TrailingWhitespace+ _ ->+ KDL.fail -< "Unknown lint rule: " <> name++ -- TODO: This should be in sync with whether the rule is LintActionNoFile+ supportsFiles = \case+ LintRule_CheckBrokenSymlinks{}+ LintRule_CheckCaseConflict{}+ LintRule_CheckMergeConflict{}+ LintRule_EndOfFileFixer{}+ LintRule_TrailingWhitespace{} ->+ True+ LintRule_NoCommitToBranch{} ->+ False+ filesDecoder' = proc rule -> do+ if supportsFiles rule+ then KDL.option [] $ KDL.children $ filesDecoder -< ()+ else do+ x <- KDL.optional $ KDL.children $ KDL.node @KDL.Node "files" -< ()+ case x of+ Just _ -> KDL.fail -< "'files' config is not supported for " <> rule.name+ Nothing -> returnA -< []++{----- PassFilesMode -----}++data PassFilesMode+ = PassFiles_None+ | PassFiles_XArgs+ | PassFiles_XArgsParallel+ | PassFiles_File+ deriving (Show, Eq)++instance KDL.DecodeValue PassFilesMode where+ valueDecoder = KDL.withDecoder KDL.valueDecoder $ \case+ "xargs" -> pure PassFiles_XArgs+ "xargs_parallel" -> pure PassFiles_XArgsParallel+ "file" -> pure PassFiles_File+ "none" -> pure PassFiles_None+ s -> KDL.failM $ "Invalid pass_files value: " <> s++{----- Files -----}++instance KDL.DecodeValue Glob where+ validValueTypeAnns _ = ["glob"]+ valueDecoder = toGlob <$> KDL.string++filesDecoder :: KDL.NodeListDecoder [Glob]+filesDecoder =+ KDL.nodeWith "files" $+ KDL.oneOf+ [ KDL.some KDL.arg+ , KDL.children $ KDL.some $ KDL.argAt "-"+ ]
+ src/Hooky/Error.hs view
@@ -0,0 +1,21 @@+module Hooky.Error (+ HookyError (..),+ abort,+ abortImpure,+) where++import Data.Text (Text)+import Data.Text qualified as Text+import UnliftIO.Exception (Exception (..), impureThrow, throwIO)++data HookyError = HookyError Text+ deriving (Show)++instance Exception HookyError where+ displayException (HookyError msg) = Text.unpack msg++abort :: Text -> IO a+abort = throwIO . HookyError++abortImpure :: Text -> a+abortImpure = impureThrow . HookyError
+ src/Hooky/Internal/GitFile.hs view
@@ -0,0 +1,255 @@+{-# LANGUAGE OverloadedRecordDot #-}+{-# LANGUAGE OverloadedStrings #-}+{-# LANGUAGE QuasiQuotes #-}+{-# LANGUAGE RecordWildCards #-}+{-# LANGUAGE StrictData #-}+{-# LANGUAGE NoFieldSelectors #-}++module Hooky.Internal.GitFile (+ -- * GitFileTarget+ GitFileTarget (..),+ GitFileTargetArg (..),+ parseGitFileTargetArg,++ -- * GitFile+ GitFile (..),+ GitFileSymlink (..),+ mkGitFileSymlink,+ resolveGitFiles,+) where++import Control.Applicative ((<|>))+import Control.Monad (guard, (<=<))+import Data.Map.Lazy (Map)+import Data.Map.Lazy qualified as Map+import Data.Maybe (catMaybes, mapMaybe)+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.Lazy qualified as LazyText+import Data.Text.Lazy.Encoding qualified as LazyText+import GHC.Records (HasField (..))+import Hooky.Error (abort)+import Hooky.Internal.Logging qualified as Logging+import Hooky.Utils.Git (GitClient)+import Hooky.Utils.OsPath qualified as OsPath+import Hooky.Utils.Process qualified as Process+import Hooky.Utils.Text qualified as Text+import System.Directory.OsPath (+ canonicalizePath,+ doesDirectoryExist,+ doesFileExist,+ getCurrentDirectory,+ getSymbolicLinkTarget,+ pathIsSymbolicLink,+ )+import System.File.OsPath qualified as OsPath+import System.IO.Unsafe (unsafeInterleaveIO)+import System.OsPath (OsPath, isAbsolute, makeRelative, osp, takeDirectory, (</>))+import UnliftIO.Exception (catchAny, fromEitherM)+import Prelude hiding (lines)++-- | The ways a user might be able to specify the files to run on.+data GitFileTarget+ = FilesGiven [GitFileTargetArg]+ | FilesModified+ | FilesStaged+ | FilesAll+ | FilesPrev+ deriving (Show, Eq)++data GitFileTargetArg+ = FileArg OsPath+ | FileArgsFrom OsPath+ deriving (Show, Eq)++parseGitFileTargetArg :: String -> GitFileTargetArg+parseGitFileTargetArg = \case+ '@' : s -> FileArgsFrom $ OsPath.fromFilePath s+ s -> FileArg $ OsPath.fromFilePath s++-- | A file that is tracked by and can be returned by git.+--+-- `git ls-files -s` can only return the following values:+-- * 100644 - Regular file, non-executable+-- * 100755 - Regular file, executable+-- * 120000 - Symbolic link+-- * 160000 - Git submodule+--+-- We filter out git submodules entirely. It's up to the hook command / each+-- `hooky lint` rule to handle symlinks appropriately.+data GitFile+ = GitFile OsPath+ | GitFile_Symlink GitFileSymlink+ deriving (Show)++instance HasField "path" GitFile OsPath where+ getField = \case+ GitFile path -> path+ GitFile_Symlink link -> link.path++data GitFileSymlink = GitFileSymlink+ { path :: OsPath+ , isDir :: ~Bool+ -- ^ Lazily fetched on first use+ , target :: ~OsPath+ -- ^ Lazily fetched on first use+ }++instance Show GitFileSymlink where+ show link = "mkGitFileSymlink " <> show link.path++mkGitFileSymlink :: OsPath -> IO GitFileSymlink+mkGitFileSymlink path = do+ isDir <- unsafeInterleaveIO $ doesDirectoryExist path+ target <- unsafeInterleaveIO $ do+ raw <- getSymbolicLinkTarget path+ -- Make the target relative to whatever `path` is relative to+ resolvePath (takeDirectory path </> raw)+ pure GitFileSymlink{..}+ where+ -- Similar to canonicalizePath, except keeps the path relative if relative+ resolvePath fp = do+ if isAbsolute fp+ then canonicalizePath fp+ else do+ cwd <- getCurrentDirectory+ makeRelative cwd <$> canonicalizePath (cwd </> fp)++-- | Resolve git information for files specified by the given 'GitFileTarget'.+resolveGitFiles :: GitClient -> GitFileTarget -> IO (Map OsPath GitFile)+resolveGitFiles git = \case+ FilesGiven files -> resolve files+ FilesModified -> getChangedFiles []+ FilesStaged -> getChangedFiles ["--staged"]+ FilesAll -> getTrackedFiles Nothing+ FilesPrev -> getChangedFiles ["HEAD~1..HEAD"]+ where+ getChangedFiles args = do+ out <- git.query (["diff", "--raw", "--diff-filter=AMR"] <> args <> ["-z"])++ -- diff --raw should output lines in the following format:+ -- :<old-mode> <new-mode> <old-hash> <new-hash> <status>\NUL<path>\NUL+ -- if <status> is C or R, there are two \NUL-separated paths instead of one.+ let parseOutput = parseStart [] . Text.splitNULs+ parseStart acc = \case+ [] -> acc+ s : rest ->+ case parseOneLine s rest of+ Just (x, rest') -> parseStart (x : acc) rest'+ Nothing ->+ Logging.traceWarn ("Unexpected line when fetching changed files: " <> Text.show s) $+ parseStart acc rest+ parseOneLine s rest = do+ [oldMode0, newMode, _oldHash, _newHash, status] <- pure $ Text.words s+ (':', _oldMode) <- Text.uncons oldMode0+ (path, rest') <-+ if any (`Text.isPrefixOf` status) ["C", "R"]+ then do+ _src : dest : rest' <- pure rest+ Just (dest, rest')+ else do+ path : rest' <- pure rest+ Just (path, rest')+ Just ((newMode, OsPath.fromText path), rest')++ toGitFileMap . parseOutput $ out++ getTrackedFiles mPaths = do+ -- Passing a large number of files to `git ls-files` is really slow,+ -- so we'll do the following:+ -- 1. If < 100 files, pass files to git in one call+ -- 2. Otherwise, load all files from git and filter in-memory+ let (modifyProc, postFilter) =+ case mPaths of+ Nothing -> (id, id)+ Just paths+ | length paths < 100 -> (withXArgs paths, id)+ | otherwise -> (id, flip Map.restrictKeys (Set.fromList paths))++ stdout <-+ fromEitherM . Process.run . Process.getOutput $+ modifyProc $+ git.proc ["ls-files", "--stage", "-z"]+ let lines = Text.splitNULs . Text.strip $ stdout+ deletedFiles <- Set.fromList . map OsPath.fromText <$> git.getLinesFrom ["ls-files", "--deleted"]++ -- ls-files --stage should output lines in the following format:+ -- <mode> <hash> <stage>TAB<path>+ let parseLine line = parseLineM line <|> Logging.traceWarn (warnMsg line) Nothing+ warnMsg line = "Unexpected line when fetching tracked files: " <> Text.show line+ parseLineM s0 = do+ (mode, s1) <- breakOn " " s0+ (_hash, s2) <- breakOn " " s1+ (_stage, path) <- breakOn "\t" s2+ Just (mode, OsPath.fromText path)+ notDeleted file@(_, path) = do+ guard $ path `Set.notMember` deletedFiles+ Just file++ fmap postFilter . toGitFileMap . mapMaybe (notDeleted <=< parseLine) $ lines++ resolve fileArgs = do+ files <-+ flip mconcatMapM fileArgs $ \case+ FileArg file -> pure [file]+ FileArgsFrom path -> map OsPath.fromText . Text.lines . Text.decodeUtf8 <$> OsPath.readFile' path++ trackedFiles <- getTrackedFiles (Just files)+ untrackedFiles <-+ mconcatMapM loadUntrackedFile . Set.toList $+ Set.fromList files Set.\\ Map.keysSet trackedFiles++ pure $ trackedFiles <> untrackedFiles++ loadUntrackedFile path =+ maybe (abort $ "File does not exist: " <> OsPath.toText path) pure <=< ifM $+ [ (,) (pathIsSymbolicLink path `catchAny` \_ -> pure False) $ do+ Map.singleton path . GitFile_Symlink <$> mkGitFileSymlink path+ , (,) (doesFileExist path) $ do+ pure . Map.singleton path $ GitFile path+ , (,) (doesDirectoryExist path) $ do+ -- All tracked files were already captured by `getTrackedFiles`, so we+ -- only need to find untracked, non-ignored files in this directory+ git.getLinesFrom ["ls-files", "--other", "--exclude-standard", OsPath.toFilePath path]+ >>= mconcatMapM (loadUntrackedFile . OsPath.fromText)+ ]++ toGitFileMap = fmap (Map.fromList . map (\file -> (file.path, file))) . mapMaybeM toGitFile+ toGitFile (mode, path) =+ case mode of+ "100644" -> pure . Just $ GitFile path+ "100755" -> pure . Just $ GitFile path+ "120000" -> Just . GitFile_Symlink <$> mkGitFileSymlink path+ "160000" -> pure Nothing+ "000000" -> pure Nothing -- deleted+ _ -> Logging.traceWarn ("Unexpected mode: " <> mode) $ pure Nothing++ withXArgs args =+ Process.setStdin (joinNULs args)+ . Process.wrap [osp|xargs|] [[osp|-0|]]+ where+ joinNULs =+ LazyText.encodeUtf8+ . LazyText.intercalate "\NUL"+ . map OsPath.toLazyText++{----- Combinators -----}++mconcatMapM :: (Monad m, Monoid b) => (a -> m b) -> [a] -> m b+mconcatMapM f = fmap mconcat . mapM f++mapMaybeM :: (Monad m) => (a -> m (Maybe b)) -> [a] -> m [b]+mapMaybeM f = fmap catMaybes . mapM f++ifM :: [(IO Bool, IO a)] -> IO (Maybe a)+ifM = \case+ (cond, action) : xs -> cond >>= \p -> if p then Just <$> action else ifM xs+ [] -> pure Nothing++breakOn :: Text -> Text -> Maybe (Text, Text)+breakOn delim s = do+ let (pre, post) = Text.breakOn delim s+ post' <- Text.stripPrefix delim post+ Just (pre, post')
+ src/Hooky/Internal/Logging.hs view
@@ -0,0 +1,97 @@+{-# LANGUAGE NamedFieldPuns #-}+{-# LANGUAGE OverloadedRecordDot #-}+{-# LANGUAGE OverloadedStrings #-}+{-# LANGUAGE NoFieldSelectors #-}++module Hooky.Internal.Logging (+ initialize,+ LogLevel (..),+ Logger,++ -- * Log methods+ debug,+ info,+ warn,+ error,++ -- * Impure log methods+ traceDebug,+ traceInfo,+ traceWarn,+ traceError,+) where++import Control.Monad (when)+import Data.IORef (IORef, newIORef, readIORef, writeIORef)+import Data.Text (Text)+import Data.Text.Lazy qualified as LazyText+import Data.Text.Lazy.IO qualified as LazyText+import Hooky.Utils.Term qualified as Term+import System.IO (stderr)+import System.IO.Unsafe (unsafePerformIO)+import Prelude hiding (error)++data LogLevel+ = LogLevel_Debug+ | LogLevel_Info+ | LogLevel_Warn+ | LogLevel_Error+ deriving (Show, Eq, Ord)++data Logger = Logger+ { level :: LogLevel+ }++newLogger :: LogLevel -> Logger+newLogger level = Logger{level}++loggerRef :: IORef Logger+loggerRef = unsafePerformIO $ newIORef (newLogger LogLevel_Warn)+{-# OPAQUE loggerRef #-}++initialize :: LogLevel -> IO ()+initialize = writeIORef loggerRef . newLogger++debug :: Text -> IO ()+debug = sendLog LogLevel_Debug++info :: Text -> IO ()+info = sendLog LogLevel_Info++warn :: Text -> IO ()+warn = sendLog LogLevel_Warn++error :: Text -> IO ()+error = sendLog LogLevel_Error++sendLog :: LogLevel -> Text -> IO ()+sendLog level msg = do+ logger <- readIORef loggerRef+ when (level >= logger.level) $ do+ LazyText.hPutStrLn stderr . levelColor level . LazyText.fromStrict $ showLevel level <> msg+ where+ showLevel = \case+ LogLevel_Debug -> "[debug] "+ LogLevel_Info -> "[info] "+ LogLevel_Warn -> "[warn] "+ LogLevel_Error -> "[error] "+ levelColor = \case+ LogLevel_Debug -> Term.gray+ LogLevel_Info -> Term.gray+ LogLevel_Warn -> Term.yellow+ LogLevel_Error -> Term.red++traceDebug :: Text -> a -> a+traceDebug = sendTrace LogLevel_Debug++traceInfo :: Text -> a -> a+traceInfo = sendTrace LogLevel_Info++traceWarn :: Text -> a -> a+traceWarn = sendTrace LogLevel_Warn++traceError :: Text -> a -> a+traceError = sendTrace LogLevel_Error++sendTrace :: LogLevel -> Text -> a -> a+sendTrace level msg a = unsafePerformIO $ sendLog level msg >> pure a
+ src/Hooky/Internal/Messages.hs view
@@ -0,0 +1,26 @@+{-# LANGUAGE OverloadedStrings #-}++module Hooky.Internal.Messages (+ render,+ log,+ info,+) where++import Data.Text.Lazy (LazyText)+import Data.Text.Lazy qualified as LazyText+import Data.Text.Lazy.IO qualified as LazyText+import Hooky.Utils.Term qualified as Term+import Prelude hiding (log)++render :: LazyText -> LazyText+render = LazyText.intercalate "\n" . onHead ("═══▶ " <>) . LazyText.splitOn "\n"+ where+ onHead f = \case+ [] -> []+ x : xs -> f x : xs++log :: LazyText -> IO ()+log = LazyText.putStrLn . Term.yellow . render++info :: LazyText -> IO ()+info = LazyText.putStrLn . Term.lightBlue . render
+ src/Hooky/Internal/Output.hs view
@@ -0,0 +1,78 @@+{-# LANGUAGE OverloadedStrings #-}++module Hooky.Internal.Output (+ -- * Outputs for running hooks+ renderHookInProgressHeader,+ renderHookInProgressBody,+ renderHookReport,++ -- * Format+ OutputFormat (..),+ allOutputFormats,+ parseOutputFormat,+ renderOutputFormat,+) where++import Data.Map qualified as Map+import Data.Text (Text)+import Data.Text.Lazy (LazyText)+import Data.Text.Lazy qualified as LazyText+import Hooky.Utils.Term qualified as Term++renderHookStatus :: Text -> LazyText -> LazyText+renderHookStatus name status =+ LazyText.concat+ [ status+ , " "+ , Term.bold $ LazyText.fromStrict name+ ]++renderHookInProgressHeader :: Text -> Int -> LazyText+renderHookInProgressHeader name time =+ LazyText.concat $+ [ start+ , " ["+ , LazyText.pack $ map getBarChar [0 .. totalWidth - 1]+ , "]\n"+ ]+ where+ totalWidth = 6 :: Int+ barWidth = 3 :: Int++ start = "╭─── " <> renderHookStatus name (Term.yellowBG "RUNNING")++ getBarChar i =+ if any (== i) . map (`mod` totalWidth) . map (time +) $ [0 .. barWidth - 1]+ then '='+ else ' '++renderHookInProgressBody :: [LazyText] -> LazyText+renderHookInProgressBody = LazyText.unlines . map ("│ " <>)++renderHookReport :: Text -> LazyText -> [LazyText] -> LazyText -> LazyText+renderHookReport name status output duration =+ LazyText.intercalate "\n" $+ (start <> "─── " <> renderHookStatus name status <> " " <> Term.gray ("(duration: " <> duration <> ")"))+ : body+ where+ start = if null output then "◈" else "╭"+ body = map ("│ " <>) output <> ["◈"]++{----- OutputFormat -----}++data OutputFormat = Format_Minimal | Format_Full | Format_Verbose+ deriving (Show, Eq, Ord, Enum, Bounded)++allOutputFormats :: [OutputFormat]+allOutputFormats = [minBound .. maxBound]++parseOutputFormat :: Text -> Maybe OutputFormat+parseOutputFormat = flip Map.lookup x+ where+ x = Map.fromList [(renderOutputFormat m, m) | m <- allOutputFormats]++renderOutputFormat :: OutputFormat -> Text+renderOutputFormat = \case+ Format_Minimal -> "minimal"+ Format_Full -> "full"+ Format_Verbose -> "verbose"
+ src/Hooky/Internal/Temp.hs view
@@ -0,0 +1,39 @@+{-# LANGUAGE QuasiQuotes #-}++module Hooky.Internal.Temp (+ hookyTmpDir,+) where++import Control.Monad (forM_, when)+import Data.Time qualified as Time+import Hooky.Utils.OsPath (listDirectoryRecur)+import System.Directory.OsPath (+ XdgDirectory (..),+ createDirectoryIfMissing,+ getModificationTime,+ getXdgDirectory,+ removePathForcibly,+ )+import System.IO.Unsafe (unsafePerformIO)+import System.OsPath (OsPath, osp)++hookyTmpDir :: OsPath+hookyTmpDir = unsafePerformIO getHookyTmpDir+{-# NOINLINE hookyTmpDir #-}++getHookyTmpDir :: IO OsPath+getHookyTmpDir = do+ now <- Time.getCurrentTime+ tmpdir <- getXdgDirectory XdgCache [osp|hooky|]+ createDirectoryIfMissing True tmpdir+ cleanup now tmpdir+ pure tmpdir+ where+ -- clean up all files older than 7 days+ cleanup now dir = do+ paths <- listDirectoryRecur dir+ forM_ paths $ \path -> do+ t <- getModificationTime path+ when (Time.addUTCTime (7 * day) t < now) $ do+ removePathForcibly path+ day = 60 * 60 * 24
+ src/Hooky/Lint.hs view
@@ -0,0 +1,337 @@+{-# 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)
+ src/Hooky/Run.hs view
@@ -0,0 +1,408 @@+{-# LANGUAGE DuplicateRecordFields #-}+{-# LANGUAGE OrPatterns #-}+{-# LANGUAGE OverloadedRecordDot #-}+{-# LANGUAGE OverloadedStrings #-}+{-# LANGUAGE NoFieldSelectors #-}++module Hooky.Run (+ RunOptions (..),+ runHooks,+) where++import Control.Concurrent (threadDelay)+import Control.Monad (forM_, unless, when)+import Data.ByteString.Lazy qualified as LazyByteString+import Data.Foldable qualified as Seq (toList)+import Data.IORef (atomicModifyIORef, newIORef, readIORef)+import Data.List.NonEmpty (NonEmpty)+import Data.List.NonEmpty qualified as NonEmpty+import Data.Map.Lazy (Map)+import Data.Map.Lazy qualified as Map+import Data.Sequence qualified as Seq+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 (LazyText)+import Data.Text.Lazy qualified as LazyText+import Data.Text.Lazy.IO qualified as LazyText+import Data.Time (diffUTCTime, getCurrentTime)+import Data.Time qualified as Time+import GHC.Records (HasField (..))+import Hooky.Config (+ Config,+ HookConfig,+ PassFilesMode (..),+ RunMode (..),+ )+import Hooky.Config qualified as Config (Config (..))+import Hooky.Config qualified as GlobalConfig (GlobalConfig (..))+import Hooky.Config qualified as HookConfig (HookConfig (..))+import Hooky.Config qualified as RepoConfig (RepoConfig (..))+import Hooky.Error (HookyError, abort)+import Hooky.Internal.GitFile (GitFile, GitFileTarget (..), resolveGitFiles)+import Hooky.Internal.Messages qualified as Messages+import Hooky.Internal.Output (+ OutputFormat (..),+ renderHookInProgressBody,+ renderHookInProgressHeader,+ renderHookReport,+ )+import Hooky.Internal.Temp (hookyTmpDir)+import Hooky.Utils.Git (GitClient)+import Hooky.Utils.Glob (matchesGlobs)+import Hooky.Utils.OsPath qualified as OsPath+import Hooky.Utils.Process (renderShell)+import Hooky.Utils.Process qualified as Process+import Hooky.Utils.Term qualified as Term+import System.Console.Regions (+ ConsoleRegion,+ closeConsoleRegion,+ displayConsoleRegions,+ finishConsoleRegion,+ setConsoleRegion,+ withConsoleRegion,+ )+import System.Console.Regions qualified as Region (RegionLayout (..))+import System.Directory (findExecutable)+import System.Exit (ExitCode (..), exitFailure)+import System.File.OsPath qualified as OsPath+import System.IO qualified as IO+import System.OsPath (OsPath, (</>))+import System.Process (getCurrentPid)+import UnliftIO.Async (pooledMapConcurrentlyN, withAsync)+import UnliftIO.Exception (+ bracket,+ catchAny,+ displayException,+ fromEitherM,+ try,+ )+import UnliftIO.Temporary (withSystemTempFile)++{----- runHooks -----}++data RunOptions = RunOptions+ { mode :: RunMode+ , hooksToRun :: Maybe (Set Text)+ , fileTarget :: GitFileTarget+ , format :: OutputFormat+ , stash :: Bool+ }++instance HasField "autofix" RunOptions Bool where+ getField options =+ case options.mode of+ Mode_Fix+ Mode_FixAdd -> True+ Mode_Check -> False++runHooks :: GitClient -> Config -> RunOptions -> IO ()+runHooks git config options = do+ (if options.stash then withStash git options.mode else id) $ do+ files <- resolveGitFiles git options.fileTarget+ let hooks =+ [ resolveHook config options files hook+ | hook <- config.repo.hooks+ , maybe True (hook.name `Set.member`) options.hooksToRun+ ]+ let checkDiffs = initDiffChecker git options.mode+ results <- runHookCmds config checkDiffs options.format maxHooks hooks+ printSummary results+ when (any ((== HookFailed) . snd) results) $ do+ exitFailure+ where+ maxHooks =+ case options.mode of+ Mode_Check -> config.global.maxParallelHooks+ Mode_Fix+ Mode_FixAdd -> 1++withStash :: GitClient -> RunMode -> IO a -> IO a+withStash git mode = bracket' saveUntracked restoreUntracked . bracket' save restore+ where+ -- bracket where the result of 'before' is passed to 'after', but not the action+ bracket' before after = bracket before after . const++ -- Stash untracked files as well+ -- Treat untracked files as intent-to-add files so they're included in the+ -- stash, then unstage them afterwards+ saveUntracked = do+ untrackedFiles <- map Text.unpack <$> git.getLinesFrom ["ls-files", "--others", "--exclude-standard"]+ if null untrackedFiles+ then pure Nothing+ else do+ git.exec $ ["add", "--intent-to-add", "--"] <> untrackedFiles+ pure $ Just untrackedFiles+ restoreUntracked = \case+ Nothing -> pure ()+ Just untrackedFiles -> do+ git.exec $ ["rm", "--cached", "--"] <> untrackedFiles++ save = do+ -- Get a phantom commit that includes staged files+ tree <- git.query ["write-tree"]++ -- Check if .hooky.kdl is to be staged+ configDiff <- git.query ["diff-index", Text.unpack tree, "--", ".hooky.kdl"]+ unless (Text.null configDiff) $ do+ abort ".hooky.kdl has changes, stage it first"++ diff <-+ fromEitherM . git.run $+ [ "diff-index"+ , "--ignore-submodules"+ , "--binary"+ , "--no-color"+ , "--no-ext-diff"+ , Text.unpack tree+ , "--"+ ]+ if Text.null diff+ then do+ pure Nothing+ else do+ pid <- getCurrentPid+ date <- Time.formatTime Time.defaultTimeLocale "%Y%m%d" <$> Time.getCurrentTime+ let stashFile = hookyTmpDir </> OsPath.fromFilePath ("stash-" <> date <> "-" <> show pid)+ OsPath.writeFile' stashFile (Text.encodeUtf8 diff)+ Messages.info $ "Stashed changes to: " <> OsPath.toLazyText stashFile+ git.clearChanges+ itaFiles <- map Text.unpack <$> git.getLinesFrom ["diff", "--name-only", "--diff-filter=A"]+ unless (null itaFiles) $ do+ git.exec $ ["rm", "--force", "--"] <> itaFiles -- Remove intent-to-add files; persisted in the diff+ pure $ Just (stashFile, itaFiles)+ restore = \case+ Nothing -> pure ()+ Just (stashFile, itaFiles) -> do+ let runGitApply =+ git.exec . concat $+ [ ["apply", "--whitespace=nowarn", OsPath.toFilePath stashFile]+ , case mode of+ Mode_FixAdd -> ["--3way"]+ _ -> ["--quiet"]+ ]+ try runGitApply >>= \case+ Right _ -> do+ Messages.info $ "Restored changes from: " <> OsPath.toLazyText stashFile+ Left (_ :: HookyError) -> do+ case mode of+ Mode_Check+ Mode_Fix -> do+ Messages.log . LazyText.unlines $+ [ "Stashed changes conflicted with hook modifications."+ , "Run `hooky fix` manually and `git add` the desired changes."+ , "Rolling back changes for now..."+ ]+ git.clearChanges+ runGitApply+ pure () -- no need to explicitly fail, since hooks should have failed+ Mode_FixAdd -> do+ Messages.log . LazyText.unlines $+ [ "Stashed changes conflicted with fixed changes."+ , "Fix conflicts after git finishes the commit."+ ]+ -- Re-apply intent-to-add state+ unless (null itaFiles) $ do+ git.exec $ ["add", "--intent-to-add", "--"] <> itaFiles++runHookCmds :: Config -> DiffChecker -> OutputFormat -> Int -> [HookCmd] -> IO [(Text, HookResult)]+runHookCmds config checkDiffs format maxHooks = displayConsoleRegions . pooledMapConcurrentlyN maxHooks run+ where+ run hook =+ withConsoleRegion Region.Linear $ \headerRegion ->+ withConsoleRegion (Region.InLine headerRegion) $ \outputRegion ->+ withAsync (renderHookHeaderAnimated headerRegion hook.name) $ \_ -> do+ hookOutput <- initHookOutput config.global.maxOutputLines $ \buf ->+ setConsoleRegion outputRegion $ renderHookInProgressBody buf+ hookOutput.log $ "Running: " <> (LazyText.fromStrict . renderShell . NonEmpty.toList) hook.args+ (result, duration) <- withDuration $ runHook checkDiffs hookOutput hook+ when (shouldShowResult format result) $ do+ hookStdout <- hookOutput.getLines+ let output = if shouldShowStdout format result then hookStdout else []+ finishConsoleRegion headerRegion $ renderHookReport hook.name result.label output duration+ closeConsoleRegion outputRegion+ pure (hook.name, result)+ withDuration action = do+ start <- getCurrentTime+ a <- action+ end <- getCurrentTime+ pure (a, LazyText.show $ end `diffUTCTime` start)++renderHookHeaderAnimated :: ConsoleRegion -> Text -> IO ()+renderHookHeaderAnimated region name = go 0+ where+ animationFPS = 12 :: Int+ go t = do+ setConsoleRegion region $ renderHookInProgressHeader name t+ threadDelay (1000000 `div` animationFPS)+ go (t + 1)++{----- HookCmd -----}++data HookCmd = HookCmd+ { name :: Text+ , args :: NonEmpty Text+ , passFiles :: PassFilesMode+ , files :: Map OsPath GitFile+ , isSkip :: Bool+ }+ deriving (Show)++resolveHook :: Config -> RunOptions -> Map OsPath GitFile -> HookConfig -> HookCmd+resolveHook config options files hookConfig =+ HookCmd+ { name = hookConfig.name+ , args =+ if options.autofix+ then hookConfig.cmdArgs `NonEmpty.appendList` hookConfig.fixArgs+ else hookConfig.cmdArgs `NonEmpty.appendList` hookConfig.checkArgs+ , passFiles = hookConfig.passFiles+ , files = Map.filterWithKey isIncluded files+ , isSkip = hookConfig.name `Set.member` config.skippedHooks+ }+ where+ isIncluded path _ =+ matchesGlobs+ (config.repo.fileGlobs <> hookConfig.fileGlobs)+ (OsPath.toText path)++runHook :: DiffChecker -> HookOutput -> HookCmd -> IO HookResult+runHook checkDiffs hookOutput hook = do+ if null hook.files || hook.isSkip+ then pure HookSkipped+ else checkDiffs hookOutput $ do+ code <-+ case hook.passFiles of+ PassFiles_None -> run hook.args+ PassFiles_XArgs -> runXargs [] hook.args+ PassFiles_XArgsParallel -> runXargs ["-P0"] hook.args+ PassFiles_File ->+ withSystemTempFile ("hooky." <> Text.unpack hook.name <> ".XXXXX") $ \fp h -> do+ forM_ hook.files $ \file -> Text.hPutStrLn h $ OsPath.toText file.path+ IO.hClose h+ run $ hook.args `NonEmpty.appendList` [Text.pack $ '@' : fp]+ pure $+ case code of+ ExitSuccess -> HookPassed+ ExitFailure _ -> HookFailed+ where+ run (cmd NonEmpty.:| args) =+ runProc cmd args ""+ runXargs xargsArgs cmdArgs =+ runProc "xargs" (["-0"] <> xargsArgs <> NonEmpty.toList cmdArgs) $+ LazyByteString.fromStrict . Text.encodeUtf8 $+ Text.concat [OsPath.toText path <> "\NUL" | path <- Map.keys hook.files]+ runProc cmd args stdin =+ (`catchAny` onProcError)+ $ Process.run+ . Process.streamOutput hookOutput.onLine+ . Process.setStderr Process.StreamStdout+ . Process.setStdin stdin+ $ Process.new (OsPath.fromText cmd) (map OsPath.fromText args)+ onProcError e = do+ -- See if it failed due to executable not being found+ let hookCmd = NonEmpty.head hook.args+ findExecutable (Text.unpack hookCmd) >>= \case+ Just _ -> pure ()+ Nothing -> abort $ "Executable does not exist: " <> hookCmd++ -- If the exception is unrecognized, just dump it to output+ abort . Text.unlines $+ [ "Failed to execute command: " <> renderShell (NonEmpty.toList hook.args)+ , Text.pack $ displayException e+ ]++{----- HookResult -----}++data HookResult = HookPassed | HookFailed | HookSkipped+ deriving (Show, Eq)++printSummary :: [(Text, HookResult)] -> IO ()+printSummary results+ | null results = pure ()+ | otherwise = do+ render HookPassed ("passed " <> Term.green "✔")+ render HookFailed ("failed " <> Term.red "✘")+ render HookSkipped ("skipped " <> Term.yellow "≫")+ where+ render status label = do+ let count = length $ filter ((== status) . snd) results+ when (count > 0) $ do+ LazyText.putStrLn . LazyText.unwords $+ [ LazyText.show count+ , if count == 1 then "hook" else "hooks"+ , label+ ]++instance HasField "label" HookResult LazyText where+ getField = \case+ HookFailed -> Term.redBG "FAIL"+ HookPassed -> Term.greenBG "PASS"+ HookSkipped -> Term.yellowBG "SKIP"++shouldShowResult :: OutputFormat -> HookResult -> Bool+shouldShowResult format = \case+ HookFailed -> format >= Format_Minimal+ HookPassed -> format >= Format_Full+ HookSkipped -> format >= Format_Full++shouldShowStdout :: OutputFormat -> HookResult -> Bool+shouldShowStdout format = \case+ HookFailed -> format >= Format_Minimal+ HookPassed -> format >= Format_Verbose+ HookSkipped -> format >= Format_Verbose++{----- HookOutput -----}++data HookOutput = HookOutput+ { onLine :: Text -> IO ()+ , log :: LazyText -> IO ()+ , getLines :: IO [LazyText]+ }++initHookOutput :: Int -> ([LazyText] -> IO ()) -> IO HookOutput+initHookOutput maxOutputLines renderBuf = do+ outputRef <- newIORef ([], Seq.empty)+ let onLine line = do+ progressLines <-+ atomicModifyIORef outputRef $ \(prev, buf) ->+ let buf' = (if Seq.length buf == maxOutputLines then Seq.drop 1 buf else buf) Seq.|> line+ in ((line : prev, buf'), Seq.toList buf')+ renderBuf progressLines+ pure+ HookOutput+ { onLine = onLine . LazyText.fromStrict+ , log = mapM_ (onLine . Term.yellow) . LazyText.lines . Messages.render+ , getLines = reverse . fst <$> readIORef outputRef+ }++{----- DiffChecker -----}++type DiffChecker = HookOutput -> IO HookResult -> IO HookResult++initDiffChecker :: GitClient -> RunMode -> DiffChecker+initDiffChecker git mode = \hookOutput action -> do+ before <- git.getDiff+ result <- action+ after <- git.getDiff+ case mode of+ _ | before == after -> do+ pure result+ Mode_Check -> do+ hookOutput.log . LazyText.unlines $+ [ "Files were unexpectedly modified."+ , "Running hooks with --mode=check should NOT modify files, since hooks are run in"+ , "parallel. Fix the commands in the hooky config to only modify files with"+ , "`fix_args`."+ ]+ pure HookFailed+ Mode_Fix -> do+ hookOutput.log "Files were modified. Run `git add` to stage the changes."+ pure HookFailed+ Mode_FixAdd -> do+ modifiedFiles <- resolveGitFiles git FilesModified+ git.exec $ "add" : [OsPath.toFilePath path | path <- Map.keys modifiedFiles]+ pure result
+ src/Hooky/Utils/Git.hs view
@@ -0,0 +1,63 @@+{-# LANGUAGE DataKinds #-}+{-# LANGUAGE OverloadedRecordDot #-}+{-# LANGUAGE QuasiQuotes #-}+{-# LANGUAGE NoFieldSelectors #-}++module Hooky.Utils.Git (+ GitClient (..),+ initGitClient,+) where++import Control.Monad (void)+import Data.Text (Text)+import Data.Text qualified as Text+import GHC.Records (HasField (..))+import Hooky.Error (HookyError (..))+import Hooky.Utils.OsPath qualified as OsPath+import Hooky.Utils.Process (Process)+import Hooky.Utils.Process qualified as Process+import Hooky.Utils.Text qualified as Text+import System.Exit (ExitCode)+import System.OsPath (OsPath, osp)+import UnliftIO.Exception (fromEitherM)++data GitClient = GitClient+ { repo :: OsPath+ }++-- | Initialize a git client at the current directory.+initGitClient :: IO GitClient+initGitClient = do+ let cwdClient =+ GitClient+ { repo = [osp|.|]+ }+ repo <- cwdClient.query ["rev-parse", "--show-toplevel"]+ pure+ GitClient+ { repo = OsPath.fromText repo+ }++instance HasField "proc" GitClient ([String] -> Process ExitCode) where+ getField git args =+ Process.new [osp|git|] . concat $+ [ [[osp|-C|], git.repo]+ , map OsPath.fromFilePath args+ ]+instance HasField "run" GitClient ([String] -> IO (Either HookyError Text)) where+ getField git args = Process.run . Process.getOutput $ git.proc args+instance HasField "exec" GitClient ([String] -> IO ()) where+ getField git args = void . fromEitherM $ git.run args+instance HasField "query" GitClient ([String] -> IO Text) where+ getField git args = fmap Text.strip . fromEitherM $ git.run args++instance HasField "getPath" GitClient (OsPath -> IO OsPath) where+ getField git path = OsPath.fromText <$> git.query ["rev-parse", "--git-path", OsPath.toFilePath path]+instance HasField "getDiff" GitClient (IO Text) where+ getField git = git.query ["diff", "--no-ext-diff", "--no-textconv", "--ignore-submodules"]+instance HasField "clearChanges" GitClient (IO ()) where+ getField git = git.exec ["checkout", "--no-recurse-submodules", "--", "."]++-- | Get lines from the output of a git command that accepts "-z"+instance HasField "getLinesFrom" GitClient ([String] -> IO [Text]) where+ getField git args = Text.splitNULs <$> git.query (args <> ["-z"])
+ src/Hooky/Utils/Glob.hs view
@@ -0,0 +1,84 @@+{-# LANGUAGE OverloadedRecordDot #-}+{-# LANGUAGE OverloadedStrings #-}+{-# LANGUAGE NoFieldSelectors #-}++module Hooky.Utils.Glob (+ Glob,+ matchesGlob,+ matchesGlobs,+ toGlob,+ renderGlob,+) where++import Data.List (partition)+import Data.Text (Text)+import Data.Text qualified as Text+import System.FilePath.Glob qualified as Glob++data Glob = Glob+ { original :: Text+ , patterns :: [Glob.Pattern]+ , invert :: Bool+ }+ deriving (Eq)++instance Show Glob where+ showsPrec _ glob = showString "toGlob " . shows (renderGlob glob)++toGlob :: Text -> Glob+toGlob s0 = parse0 s0+ where+ parse0 s =+ case Text.uncons s of+ Just ('!', s') -> (parse1 s'){invert = True}+ _ -> parse1 s++ parse1 s =+ case Text.uncons s of+ Just ('/', s') -> parse2 s'+ _ -> parse2 ("**/" <> s)++ parse2 s =+ Glob+ { original = s0+ , patterns = map (Glob.compile . Text.unpack) $ expandBraces s+ , invert = False+ }++ -- Glob doesn't support braces, so we have to manually expand+ -- https://github.com/Deewiant/glob/issues/32+ expandBraces s+ | Just (pre, s') <- breakAt "{" s+ , Just (braced, post) <- breakAt "}" s' =+ [ pre <> braced' <> post'+ | braced' <- Text.splitOn "," braced+ , post' <- expandBraces post+ ]+ | otherwise = [s]++ breakAt sep s =+ let (pre, post) = Text.breakOn sep s+ in (pre,) <$> Text.stripPrefix sep post++renderGlob :: Glob -> Text+renderGlob = (.original)++matchesGlob :: Glob -> Text -> Bool+matchesGlob glob s = invert $ any matches glob.patterns+ where+ invert = if glob.invert then not else id+ matches = flip (Glob.matchWith matchOpts) (Text.unpack s)+ matchOpts =+ Glob.matchPosix+ { Glob.matchDotsImplicitly = True+ }++matchesGlobs :: [Glob] -> Text -> Bool+matchesGlobs globs s =+ and+ [ null posGlobs || any matches posGlobs+ , null negGlobs || all matches negGlobs+ ]+ where+ matches = (`matchesGlob` s)+ (negGlobs, posGlobs) = partition (.invert) globs
+ src/Hooky/Utils/OsPath.hs view
@@ -0,0 +1,82 @@+module Hooky.Utils.OsPath (+ -- * Conversions+ fromFilePath,+ toFilePath,+ fromText,+ toText,+ toLazyText,++ -- * Pure+ parents,++ -- * IO+ listDirectoryRecur,+) where++import Control.Monad (forM)+import Data.ByteString.Short qualified as ByteString.Short+import Data.Coerce (coerce)+import Data.Text (Text)+import Data.Text qualified as Text+import Data.Text.Encoding qualified as Text++-- Needed to `coerce`++import Data.Text.Lazy (LazyText)+import Data.Text.Lazy qualified as LazyText+import Hooky.Error (abortImpure)+import System.Directory.OsPath (doesDirectoryExist, listDirectory)+import System.OsPath (OsPath, (</>))+import System.OsPath qualified as OsPath+import System.OsString qualified as OsString+import System.OsString.Internal.Types (+ OsString (..),+ PosixString (..),+ )+import UnliftIO.Exception (displayException)++fromFilePath :: FilePath -> OsPath+fromFilePath s =+ case OsPath.encodeUtf s of+ Right p -> p+ Left e -> abortImpure . Text.pack $ "Invalid path: " <> show s <> "\n" <> displayException e++toFilePath :: OsPath -> FilePath+toFilePath p =+ case OsPath.decodeUtf p of+ Right s -> s+ Left e -> abortImpure . Text.pack $ "Invalid path: " <> show p <> "\n" <> displayException e++-- https://hackage-content.haskell.org/package/unwitch-3.1.0/docs/src/Unwitch.Convert.Text.html#toOsString+fromText :: Text -> OsPath+fromText =+ case OsString.coercionToPlatformTypes of+ Left{} -> coerce . ByteString.Short.toShort . Text.encodeUtf16LE+ Right{} -> coerce . ByteString.Short.toShort . Text.encodeUtf8++toText :: OsPath -> Text+toText =+ case OsString.coercionToPlatformTypes of+ Left{} -> Text.decodeUtf16LE . ByteString.Short.fromShort . coerce+ Right{} -> Text.decodeUtf8 . ByteString.Short.fromShort . coerce++toLazyText :: OsPath -> LazyText+toLazyText = LazyText.fromStrict . toText++parents :: OsPath -> [OsPath]+parents = untilFixed . iterate OsPath.takeDirectory+ where+ untilFixed :: (Eq a) => [a] -> [a]+ untilFixed = \case+ [] -> []+ x0 : xs -> x0 : (map snd . takeWhile (\(prev, x) -> prev /= x) $ zip (x0 : xs) xs)++listDirectoryRecur :: OsPath -> IO [OsPath]+listDirectoryRecur dir = do+ names <- listDirectory dir+ fmap concat . forM names $ \name -> do+ let path = dir </> name+ isDir <- doesDirectoryExist path+ if isDir+ then listDirectoryRecur path+ else pure [path]
+ src/Hooky/Utils/Process.hs view
@@ -0,0 +1,144 @@+{-# LANGUAGE NamedFieldPuns #-}+{-# LANGUAGE OverloadedRecordDot #-}+{-# LANGUAGE OverloadedStrings #-}+{-# LANGUAGE NoFieldSelectors #-}++module Hooky.Utils.Process (+ -- * Running processes; meant to be imported qualified+ Process,+ StreamOut (..),+ new,+ run,+ wrap,+ setStdin,+ setStderr,+ getOutput,+ streamOutput,++ -- * Utilities+ renderShell,+) where++import Data.ByteString.Lazy (LazyByteString)+import Data.ByteString.Lazy qualified as LazyByteString+import Data.Char (isSpace)+import Data.Text (Text)+import Data.Text qualified as Text+import Data.Text.IO qualified as Text+import Hooky.Error (HookyError (..))+import Hooky.Internal.Logging qualified as Logging+import Hooky.Utils.OsPath qualified as OsPath+import System.Exit (ExitCode (..))+import System.IO qualified as IO+import System.OsString (OsString)+import System.Process qualified as Process+import UnliftIO.Async (withAsync)+import UnliftIO.Async qualified as Async++{----- Running processes -----}++data Process a = Process+ { cmd :: OsString+ , args :: [OsString]+ , populateStdin :: IO.Handle -> IO ()+ , stderr :: StreamOut+ , callback :: Process.ProcessHandle -> IO.Handle -> IO.Handle -> IO a+ }++data StreamOut+ = StreamStdout+ | StreamStderr++new :: OsString -> [OsString] -> Process ExitCode+new cmd args =+ Process+ { cmd+ , args+ , populateStdin = \_ -> pure ()+ , stderr = StreamStderr+ , callback = \h _ _ -> Process.waitForProcess h+ }++run :: Process a -> IO a+run proc = do+ Logging.debug $ "Running proc: " <> Text.show (proc.cmd : proc.args)++ (stdin_r, stdin_w) <- Process.createPipe+ (stdout_r, stdout_w) <- Process.createPipe+ (stderr_r, stderr_w) <-+ case proc.stderr of+ StreamStdout -> pure (stdout_r, stdout_w)+ StreamStderr -> Process.createPipe+ IO.hSetEncoding stdout_r IO.utf8+ IO.hSetEncoding stderr_r IO.utf8++ Process.withCreateProcess+ (Process.proc (OsPath.toFilePath proc.cmd) (map OsPath.toFilePath proc.args))+ { Process.std_in = Process.UseHandle stdin_r+ , Process.std_out = Process.UseHandle stdout_w+ , Process.std_err = Process.UseHandle stderr_w+ , Process.close_fds = True+ }+ ( \_ _ _ h -> do+ proc.populateStdin stdin_w+ IO.hClose stdin_w+ proc.callback h stdout_r stderr_r+ )++wrap :: OsString -> [OsString] -> Process a -> Process a+wrap cmd args proc =+ proc+ { cmd+ , args = args <> (proc.cmd : proc.args)+ }++setStdin :: LazyByteString -> Process a -> Process a+setStdin bs proc = proc{populateStdin = \h -> LazyByteString.hPutStr h bs}++setStderr :: StreamOut -> Process a -> Process a+setStderr stream proc = proc{stderr = stream}++getOutput :: Process a -> Process (Either HookyError Text)+getOutput proc = proc{callback}+ where+ callback h stdoutH stderrH = do+ -- Fork a thread to consume the pipes, so they don't get blocked+ withAsync (Text.hGetContents stdoutH) $ \stdoutAsync -> do+ Async.link stdoutAsync+ withAsync (Text.hGetContents stderrH) $ \stderrAsync -> do+ Async.link stderrAsync++ code <- Process.waitForProcess h+ stdout <- Async.wait stdoutAsync+ stderr <- Async.wait stderrAsync+ case code of+ ExitSuccess -> do+ pure $ Right stdout+ ExitFailure n -> do+ pure . Left . HookyError . Text.unlines $+ [ "command exited with code " <> Text.show n <> ": " <> Text.show (proc.cmd : proc.args)+ , stderr+ ]++streamOutput :: (Text -> IO ()) -> Process a -> Process a+streamOutput onOutputLine proc = proc{callback}+ where+ callback h stdoutH stderrH = do+ streamFrom stdoutH+ proc.callback h stdoutH stderrH+ streamFrom h = do+ eof <- IO.hIsEOF h+ if eof+ then pure ()+ else do+ Text.hGetLine h >>= onOutputLine+ streamFrom h++{----- Utilities -----}++renderShell :: [Text] -> Text+renderShell args =+ Text.intercalate " " $+ [ if Text.any isSpace s then "'" <> s <> "'" else s+ | s <- args+ ]
+ src/Hooky/Utils/Term.hs view
@@ -0,0 +1,63 @@+module Hooky.Utils.Term (+ -- * Utilities for styling terminal output+ TextWrapper,+ bold,+ green,+ lightBlue,+ red,+ yellow,+ gray,+ greenBG,+ redBG,+ yellowBG,+) where++import Data.Text.Lazy (LazyText)+import Data.Text.Lazy qualified as LazyText+import System.Console.ANSI (+ ColorIntensity (..),+ ConsoleIntensity (..),+ ConsoleLayer (..),+ SGR (..),+ setSGRCode,+ )+import System.Console.ANSI qualified as ANSI++{----- Output -----}++type TextWrapper = LazyText -> LazyText++wrapSGR :: [SGR] -> TextWrapper+wrapSGR codes s =+ LazyText.concat+ [ LazyText.pack $ setSGRCode codes+ , s+ , LazyText.pack $ setSGRCode [Reset]+ ]++bold :: TextWrapper+bold = wrapSGR [SetConsoleIntensity BoldIntensity]++green :: TextWrapper+green = wrapSGR [SetColor Foreground Vivid ANSI.Green]++lightBlue :: TextWrapper+lightBlue = wrapSGR [SetPaletteColor Foreground 81]++red :: TextWrapper+red = wrapSGR [SetColor Foreground Vivid ANSI.Red]++yellow :: TextWrapper+yellow = wrapSGR [SetColor Foreground Dull ANSI.Yellow]++gray :: TextWrapper+gray = wrapSGR [SetPaletteColor Foreground 8]++greenBG :: TextWrapper+greenBG = wrapSGR [SetColor Background Dull ANSI.Green]++redBG :: TextWrapper+redBG = wrapSGR [SetColor Background Dull ANSI.Red]++yellowBG :: TextWrapper+yellowBG = wrapSGR [SetColor Background Dull ANSI.Yellow]
+ src/Hooky/Utils/Text.hs view
@@ -0,0 +1,12 @@+{-# LANGUAGE OverloadedStrings #-}++module Hooky.Utils.Text (+ splitNULs,+) where++import Data.Text (Text)+import Data.Text qualified as Text++-- | Like 'Text.words', except splits '\NUL'+splitNULs :: Text -> [Text]+splitNULs = filter (not . Text.null) . Text.splitOn "\NUL"
+ src/Main.hs view
@@ -0,0 +1,486 @@+{-# 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
+ test/Hooky/ConfigSpec.hs view
@@ -0,0 +1,154 @@+{-# LANGUAGE MultilineStrings #-}+{-# LANGUAGE OverloadedStrings #-}++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 Hooky.Config qualified as HookConfig (HookConfig (..))+import Hooky.Config qualified as RepoConfig (RepoConfig (..))+import Hooky.Utils.Glob (toGlob)+import Skeletest+import Skeletest.Predicate qualified as P++spec :: Spec+spec = do+ defaultsSpec+ hookSpec+ lintRulesSpec++defaultsSpec :: Spec+defaultsSpec = do+ describe "defaults" $ do+ describe "files" $ do+ it "supports specifying as args" $ do+ let input =+ """+ defaults {+ files *.hs *.md+ }+ """+ expected =+ emptyRepoConfig+ { RepoConfig.fileGlobs = [toGlob "*.hs", toGlob "*.md"]+ }+ parseRepoConfig input `shouldBe` Right expected++ it "supports specifying as list" $ do+ let input =+ """+ defaults {+ files {+ - *.hs+ - *.md+ }+ }+ """+ expected =+ emptyRepoConfig+ { RepoConfig.fileGlobs = [toGlob "*.hs", toGlob "*.md"]+ }+ parseRepoConfig input `shouldBe` Right expected++hookSpec :: Spec+hookSpec = do+ describe "defaults" $ do+ describe "files" $ do+ it "supports specifying as args" $ do+ let input =+ """+ hook myHook {+ command foo+ files *.hs *.md+ }+ """+ expected =+ emptyRepoConfig+ { RepoConfig.hooks =+ [ (toHookConfig "myHook" ["foo"])+ { HookConfig.fileGlobs = [toGlob "*.hs", toGlob "*.md"]+ }+ ]+ }+ parseRepoConfig input `shouldBe` Right expected++ it "supports specifying as list" $ do+ let input =+ """+ hook myHook {+ command foo+ files {+ - *.hs+ - *.md+ }+ }+ """+ expected =+ emptyRepoConfig+ { RepoConfig.hooks =+ [ (toHookConfig "myHook" ["foo"])+ { HookConfig.fileGlobs = [toGlob "*.hs", toGlob "*.md"]+ }+ ]+ }+ parseRepoConfig input `shouldBe` Right expected++lintRulesSpec :: Spec+lintRulesSpec = do+ describe "lint_rules" $ do+ describe "check_broken_symlinks" $ do+ supportsFiles "check_broken_symlinks"++ describe "check_case_conflict" $ do+ supportsFiles "check_case_conflict"++ describe "check_merge_conflict" $ do+ supportsFiles "check_merge_conflict"++ describe "end_of_file_fixer" $ do+ supportsFiles "end_of_file_fixer"++ describe "no_commit_to_branch" $ do+ doesntSupportFiles "no_commit_to_branch"++ describe "trailing_whitespace" $ do+ supportsFiles "trailing_whitespace"+ where+ supportsFiles rule = do+ it "supports specifying 'files' with args" $ do+ parseRepoConfig ("lint_rules { - " <> rule <> " { files *.txt; }; }")+ `shouldSatisfy` P.right P.anything++ it "supports specifying 'files' with list" $ do+ parseRepoConfig ("lint_rules { - " <> rule <> " { files { - *.txt; }; }; }")+ `shouldSatisfy` P.right P.anything++ doesntSupportFiles rule = do+ 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
@@ -0,0 +1,355 @@+{-# LANGUAGE MultilineStrings #-}+{-# LANGUAGE OverloadedRecordDot #-}+{-# LANGUAGE OverloadedStrings #-}++module Hooky.E2ESpec (spec) where++import Control.Monad (forM_, (<=<))+import Data.Text (Text)+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.Hooky (HookyExe (..))+import Skeletest+import Skeletest.Predicate qualified as P+import System.Directory (+ createDirectory,+ createDirectoryLink,+ createFileLink,+ removeFile,+ renameFile,+ )+import System.Exit (ExitCode (..))+import System.FilePath ((</>))+import System.IO qualified as IO+import System.Process qualified as Process+import System.Timeout (timeout)++spec :: Spec+spec = do+ describe "git commit" $ do+ it "runs hooky" . withGitRepo $ \git -> do+ writeFile ".hooky.kdl" hookyConfigEofFixer+ writeFile "good.txt" "good\n"+ writeFile "bad.txt" "bad"+ runHooky ["install"] `shouldSatisfy` P.returns (P.eq ExitSuccess)+ git.exec ["add", ".hooky.kdl", "good.txt", "bad.txt"]+ (code0, _, stderr0) <- git.run ["commit", "-m", "initial commit"]+ code0 `shouldBe` ExitFailure 1+ stderr0 `shouldSatisfy` P.hasInfix "1 hook failed"+ stderr0 `shouldNotSatisfy` P.hasInfix "[warn]"++ writeFile "bad.txt" "bad\n"+ git.exec ["add", "bad.txt"]+ (code1, _, stderr1) <- git.run ["commit", "-m", "commit"]+ code1 `shouldBe` ExitSuccess+ stderr1 `shouldSatisfy` P.hasInfix "1 hook passed"+ stderr1 `shouldNotSatisfy` P.hasInfix "[warn]"++ describe "hooky run" $ do+ it "defaults to --stash --staged" $ do+ withGitRepo $ \git -> do+ commitHookyEofFixer git+ writeFile "good.txt" "good\n"+ writeFile "bad-in-stage.txt" "bad"+ writeFile "bad-untracked.txt" "bad"+ git.exec ["add", "good.txt", "bad-in-stage.txt"]+ writeFile "bad-in-stage.txt" "good\n"+ runHooky ["run"] `shouldSatisfy` P.returns (P.eq (ExitFailure 1))++ withGitRepo $ \git -> do+ commitHookyEofFixer git+ writeFile "good.txt" "good\n"+ writeFile "bad-modified.txt" "good\n"+ writeFile "bad-untracked.txt" "bad"+ git.exec ["add", "good.txt", "bad-modified.txt"]+ writeFile "bad-modified.txt" "bad"+ runHooky ["run"] `shouldSatisfy` P.returns (P.eq ExitSuccess)++ it "errors if multiple file selection flags are passed" $ do+ (code, _, stderr) <- readHooky ["run", "--all", "--modified"]+ code `shouldBe` ExitFailure 1+ stderr `shouldBe` "Expected exactly one of: FILES, --modified, --staged, --all, --prev\n"++ it "errors if file argument and flags are both passed" $ do+ (code, _, stderr) <- readHooky ["run", "--all", "file.txt"]+ code `shouldBe` ExitFailure 1+ stderr `shouldBe` "Expected exactly one of: FILES, --modified, --staged, --all, --prev\n"++ it "filters out deleted files" $ do+ withGitRepo $ \git -> do+ commitHookyEofFixer git+ writeFile "bad.txt" "bad"+ git.exec ["add", "bad.txt"] >> git.exec ["commit", "-m", "test"]+ removeFile "bad.txt"+ runHooky ["run", "--all"] `shouldSatisfy` P.returns (P.eq ExitSuccess)++ it "works on files with whitespace in name" $ do+ withGitRepo $ \git -> do+ commitHookyEofFixer git+ writeFile "foo bar.txt" "bad"+ git.exec ["add", "foo bar.txt"]+ runHooky ["run", "-a"] `shouldSatisfy` P.returns (P.eq (ExitFailure 1))+ writeFile "foo bar.txt" "good\n"+ git.exec ["add", "foo bar.txt"]+ runHooky ["run", "-a"] `shouldSatisfy` P.returns (P.eq ExitSuccess)++ it "works after `git mv`" $ do+ withGitRepo $ \git -> do+ commitHookyEofFixer git+ writeFile "good.txt" ""+ git.exec ["add", "good.txt"] >> git.exec ["commit", "-m", "test"]+ git.exec ["mv", "good.txt", "good-moved.txt"]+ runHooky ["run"] `shouldSatisfy` P.returns (P.eq ExitSuccess)++ it "stashes intent-to-add files" $ do+ withGitRepo $ \git -> do+ commitHookyEofFixer git+ writeFile "bad.txt" "bad"+ git.exec ["add", "-N", "bad.txt"]+ let checkIntentToAdd = do+ (_, stdout, _) <- git.run ["diff-files", "--name-only", "--diff-filter=A"]+ stdout `shouldBe` "bad.txt"+ readFile "bad.txt" `shouldSatisfy` P.returns (P.eq "bad")+ checkIntentToAdd+ runHooky ["run", "--stash", "--all"] `shouldSatisfy` P.returns (P.eq ExitSuccess)+ checkIntentToAdd++ it "stashes untracked files" $ do+ withGitRepo $ \git -> do+ commitHookyEofFixer git+ writeFile "bad.txt" "bad"+ let checkUntracked = do+ (_, stdout, _) <- git.run ["ls-files", "--others", "--exclude-standard"]+ stdout `shouldBe` "bad.txt"+ readFile "bad.txt" `shouldSatisfy` P.returns (P.eq "bad")+ checkUntracked+ runHooky ["run", "--stash", "--all"] `shouldSatisfy` P.returns (P.eq ExitSuccess)+ checkUntracked++ it "stashes unstaged renamed files" $ do+ withGitRepo $ \git -> do+ commitHookyEofFixer git+ writeFile "test1.txt" "test\n"+ writeFile "test2.txt" "test\n"+ git.exec ["add", "test1.txt", "test2.txt"]+ git.exec ["commit", "-m", "test"]+ -- Rename test{1,2}.txt => test{1,2}-new.txt;+ -- Intent-to-add `test1-new.txt`, leave `test2-new.txt` untracked+ renameFile "test1.txt" "test1-new.txt"+ renameFile "test2.txt" "test2-new.txt"+ git.exec ["add", "-N", "test2-new.txt"]+ (_, before, _) <- git.run ["status"]+ runHooky ["run"] `shouldSatisfy` P.returns (P.eq ExitSuccess)+ (_, after, _) <- git.run ["status"]+ after `shouldBe` before++ it "error if .hooky.kdl is to be stashed" $ do+ withGitRepo $ \git -> do+ commitHookyEofFixer git+ writeFile ".hooky.kdl" $ hookyConfigEofFixer <> "\n\n\n"+ (code, _, stderr) <- readHooky ["run", "--stash", "--staged"]+ code `shouldBe` ExitFailure 1+ stderr `shouldBe` ".hooky.kdl has changes, stage it first\n"++ forM_ allOutputFormats $ \format -> do+ let flag = Text.unpack $ "--format=" <> renderOutputFormat format+ scrubDuration s =+ case Text.breakOn "duration: " s of+ (_, "") -> s+ (pre, post) -> pre <> "duration: XX.XXXs" <> scrubDuration (Text.dropWhile (/= '\n') post)+ -- https://github.com/brandonchinn178/hooky/issues/9+ skip "until we can set --max-parallel-hooks 1" . it ("outputs " <> flag) $ do+ (code, stdout, _) <-+ withGitRepo $ \git -> do+ writeFile ".hooky.kdl" $+ """+ hook hooky_pass {+ command hooky lint+ files *.pass+ }+ hook hooky_fail {+ command hooky lint+ files *.fail+ }+ hook hooky_skip {+ command hooky lint+ files *.skip+ }+ lint_rules {+ - end_of_file_fixer+ }++ """+ writeFile "file.pass" "good\n"+ writeFile "file.fail" "bad"+ git.exec ["add", "."]+ readHooky ["run", "--all", flag]+ code `shouldBe` ExitFailure 1+ scrubDuration stdout `shouldSatisfy` P.matchesSnapshot++ it "runs on all files in directory" $ do+ withGitRepo $ \git -> do+ commitHookyEofFixer git+ createDirectory "foo"+ writeFile "foo/bar.txt" "asdf"+ (code, stdout, _) <- readHooky ["run", "foo"]+ code `shouldBe` ExitFailure 1+ stdout `shouldSatisfy` P.hasInfix "foo/bar.txt"++ it "treats symlinked files as a symlink" $ do+ withGitRepo $ \git -> do+ commitHookyEofFixer git+ writeFile "foo.txt" "bad"+ createFileLink "foo" "foo-link"+ (code, _, _) <- readHooky ["run", "foo-link"]+ code `shouldBe` ExitSuccess++ it "treats symlinked directories as a symlink" $ do+ withGitRepo $ \git -> do+ commitHookyEofFixer git+ createDirectory "foo"+ createDirectoryLink "foo" "foo-link"+ writeFile "foo/bar.txt" "bad"+ (code, _, _) <- readHooky ["run", "foo-link"]+ code `shouldBe` ExitSuccess++ it "runs on all files in implicit symlinked directory" $ do+ withGitRepo $ \git -> do+ writeFile ".hooky.kdl" $+ """+ hook hooky {+ command hooky lint {+ // Bug appears only when `pass_files` is `file`+ pass_files file+ }+ files *+ }+ lint_rules {+ - end_of_file_fixer+ }++ """+ git.exec ["add", ".hooky.kdl"]+ git.exec ["commit", "-m", "test"]+ createDirectory "foo"+ createDirectoryLink "foo" "foo-link"+ writeFile "foo/bar.txt" ""+ git.exec ["add", "foo", "foo-link"]+ (code, _, _) <- readHooky ["run"]+ code `shouldBe` ExitSuccess++ describe "skipping hooks with env var" $ do+ let runHookyWithEnv env args = do+ HookyExe hooky <- getFixture+ Process.withCreateProcess (Process.proc "env" $ [env, hooky] <> args) $ \_ _ _ h -> do+ Process.waitForProcess h+ it "skips entire hook" $ do+ withGitRepo $ \git -> do+ writeFile ".hooky.kdl" $+ """+ hook hooky1 {+ command hooky lint+ files *.good+ }+ hook hooky2 {+ command hooky lint+ files *.bad+ }+ lint_rules {+ - end_of_file_fixer+ }++ """+ writeFile "test.good" "test\n"+ writeFile "test.bad" "test"+ git.exec ["add", "."]+ runHookyWithEnv "SKIP=hooky2" ["run", "--all"] `shouldSatisfy` P.returns (P.eq ExitSuccess)++ it "skips hooky lint rules" $ do+ withGitRepo $ \git -> do+ writeFile ".hooky.kdl" $+ """+ hook hooky {+ command hooky lint+ files *+ }+ lint_rules {+ - end_of_file_fixer+ }++ """+ writeFile "test.txt" "test"+ git.exec ["add", "."]+ runHookyWithEnv "SKIP=end_of_file_fixer" ["run", "--all"] `shouldSatisfy` P.returns (P.eq ExitSuccess)++ describe "hooky lint" $ do+ it "works on large repos using pass_files=file" $ do+ withGitRepo $ \git -> do+ writeFile ".hooky.kdl" $+ """+ hook hooky {+ command hooky lint {+ pass_files file+ }+ files *+ }+ lint_rules {+ - end_of_file_fixer+ }++ """+ -- 10,000 files, each with 200 character paths+ -- should trigger "posix_spawnp: resource exhausted (Argument list too long)"+ forM_ [1 .. 100 :: Int] $ \x -> do+ let dir = Text.unpack $ Text.replicate 100 "a" <> Text.show x+ createDirectory dir+ forM_ [1 .. 100 :: Int] $ \y -> do+ let file = Text.unpack $ Text.replicate 100 "b" <> Text.show y+ writeFile (dir </> file) ""+ git.exec ["add", "."]+ git.exec ["commit", "-m", "test", "-q"]++ maybe (failTest "Timed out") pure <=< timeout 2_000_000 $ do+ code <- runHooky ["run", "-a", "--format=verbose"]+ code `shouldBe` ExitSuccess++runHooky :: [String] -> IO ExitCode+runHooky args = do+ HookyExe hooky <- getFixture+ Process.withCreateProcess (Process.proc hooky args) $ \_ _ _ h -> do+ Process.waitForProcess h++readHooky :: [String] -> IO (ExitCode, Text, Text)+readHooky args = do+ HookyExe hooky <- getFixture+ (code, stdoutS, stderrS) <- Process.readProcessWithExitCode hooky args ""+ 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)++commitHookyEofFixer :: TestGitClient -> IO ()+commitHookyEofFixer git = do+ writeFile ".hooky.kdl" hookyConfigEofFixer+ git.exec ["add", ".hooky.kdl"]+ git.exec ["commit", "-m", "test"]++hookyConfigEofFixer :: String+hookyConfigEofFixer =+ """+ hook hooky {+ command hooky lint+ files *+ }+ lint_rules {+ - end_of_file_fixer+ }++ """
+ test/Hooky/LintSpec.hs view
@@ -0,0 +1,427 @@+{-# LANGUAGE DisambiguateRecordFields #-}+{-# LANGUAGE OverloadedRecordDot #-}+{-# LANGUAGE OverloadedStrings #-}+{-# LANGUAGE QuasiQuotes #-}++module Hooky.LintSpec (spec) where++import Control.Monad (forM_, (<=<))+import Data.Map (Map)+import Data.Map.Lazy qualified as Map+import Data.Text (Text)+import Hooky.Config (Config (..), RepoConfig (..))+import Hooky.Config qualified as LintRule (LintRule (..))+import Hooky.Internal.GitFile (GitFile (..))+import Hooky.Lint (+ LintOptions (..),+ LintRule (..),+ LintRuleRule (..),+ lintReportSuccess,+ renderLintReport,+ runLintRules,+ toGlob,+ )+import Hooky.TestUtils.Git (withGitRepo)+import Hooky.Utils.OsPath qualified as OsPath+import Skeletest+import Skeletest.Predicate qualified as P+import System.Directory (+ createDirectory,+ createDirectoryIfMissing,+ createDirectoryLink,+ createFileLink,+ getCurrentDirectory,+ removeFile,+ )+import System.FilePath ((</>))+import System.OsPath (OsPath, osp)+import System.Timeout (timeout)+import UnliftIO.Exception (SomeException)++spec :: Spec+spec = do+ describe "check_broken_symlinks" $ do+ let config = defaultConfig LintRule_CheckBrokenSymlinks++ it "succeeds when all symlinks are valid" $ do+ report <-+ withGitRepo $ \git -> do+ writeFile "foo.txt" "example"+ createFileLink "foo.txt" "foo-link.txt"+ git.exec ["add", "foo.txt", "foo-link.txt"]+ runLintRules git.client config defaultOptions+ lintReportSuccess report `shouldBe` True++ it "handles symlinks to directories" $ do+ report <-+ withGitRepo $ \git -> do+ createDirectory "foo"+ writeFile "foo/bar.txt" ""+ createDirectoryLink "foo" "foo-link"+ git.exec ["add", "foo", "foo-link"]+ runLintRules git.client config defaultOptions+ lintReportSuccess report `shouldBe` True++ it "handles symlinks to directory ancestors" $ do+ report <-+ withGitRepo $ \git -> do+ createDirectory "foo"+ createDirectory "foo/bar"+ writeFile "foo/bar/file.txt" ""+ createDirectoryLink "foo" "foo-link"+ git.exec ["add", "foo", "foo-link"]+ runLintRules git.client config defaultOptions+ lintReportSuccess report `shouldBe` True++ it "handles relative path symlinks" $ do+ report <-+ withGitRepo $ \git -> do+ createDirectory "subdir"+ createDirectory "subdir/subdir2"+ -- subdir/top-level-link.txt -> ../top-level.txt+ writeFile "top-level.txt" ""+ createFileLink "../top-level.txt" "subdir/top-level-link.txt"+ -- subdir/nested-link.txt -> nested.txt+ writeFile "subdir/nested.txt" ""+ createFileLink "nested.txt" "subdir/nested-link.txt"+ git.exec ["add", "top-level.txt", "subdir"]+ runLintRules git.client config defaultOptions+ lintReportSuccess report `shouldBe` True++ it "handles symlink with .. in deep symlink" $ do+ report <-+ withGitRepo $ \git -> do+ createDirectoryIfMissing True "subdir1/subdir2/subdir3"+ writeFile "subdir1/subdir2/nested.txt" ""+ writeFile "subdir1/subdir2/subdir3/.gitkeep" ""+ createFileLink "subdir1/subdir2/subdir3" "deep-link"+ createFileLink "deep-link/../nested.txt" "nested-link.txt"+ git.exec ["add", "subdir1", "deep-link", "nested-link.txt"]+ runLintRules git.client config defaultOptions+ lintReportSuccess report `shouldBe` True++ it "fails when a symlink is broken" $ do+ report <-+ withGitRepo $ \git -> do+ createFileLink "foo.txt" "foo-link.txt"+ git.exec ["add", "foo-link.txt"]+ runLintRules git.client config defaultOptions+ lintReportSuccess report `shouldBe` False+ renderLintReport report `shouldSatisfy` P.matchesSnapshot++ it "fails when target is not tracked" $ do+ report <-+ withGitRepo $ \git -> do+ writeFile "foo.txt" "example"+ createFileLink "foo.txt" "foo-link.txt"+ git.exec ["add", "foo-link.txt"]+ runLintRules git.client config defaultOptions+ lintReportSuccess report `shouldBe` False++ it "fails when target is deleted" $ do+ report <-+ withGitRepo $ \git -> do+ writeFile "foo.txt" "example"+ createFileLink "foo.txt" "foo-link.txt"+ git.exec ["add", "foo.txt", "foo-link.txt"]+ git.exec ["commit", "-m", "Initial commit"]+ git.exec ["rm", "foo.txt"]+ runLintRules git.client config defaultOptions+ lintReportSuccess report `shouldBe` False++ it "fails when target is absolute path" $ do+ report <-+ withGitRepo $ \git -> do+ root <- getCurrentDirectory+ writeFile "foo.txt" ""+ createFileLink (root </> "foo.txt") "foo-link.txt"+ git.exec ["add", "foo.txt", "foo-link.txt"]+ runLintRules git.client config defaultOptions+ lintReportSuccess report `shouldBe` False++ it "skips files failing glob" . withGitRepo $ \git -> do+ createFileLink "foo.txt" "foo-link.txt"+ git.exec ["add", "foo-link.txt"]+ report <-+ runLintRules+ git.client+ (withFiles ["!*.txt"] config)+ defaultOptions+ lintReportSuccess report `shouldBe` True++ describe "check_case_conflict" $ do+ let config = defaultConfig LintRule_CheckCaseConflict++ it "succeeds when no files conflict" $ do+ report <-+ withGitRepo $ \git -> do+ writeFile "foo.txt" ""+ writeFile "bar.txt" ""+ git.exec ["add", "foo.txt", "bar.txt"]+ runLintRules git.client config defaultOptions+ lintReportSuccess report `shouldBe` True++ it "fails when files conflict" $ do+ report <-+ withGitRepo $ \git -> do+ git.exec ["config", "core.ignorecase", "false"]+ writeFile "foo.txt" ""+ git.exec ["add", "foo.txt"]+ removeFile "foo.txt"+ writeFile "FOO.TXT" ""+ git.exec ["add", "FOO.TXT"]+ git.exec ["checkout", "foo.txt"]+ runLintRules git.client config defaultOptions+ lintReportSuccess report `shouldBe` False+ renderLintReport report `shouldSatisfy` P.matchesSnapshot++ it "fails when new file conflicts" $ do+ report <-+ withGitRepo $ \git -> do+ git.exec ["config", "core.ignorecase", "false"]+ writeFile "foo.txt" ""+ git.exec ["add", "foo.txt"]+ git.exec ["commit", "-m", "Initial commit"]+ removeFile "foo.txt"+ writeFile "FOO.TXT" ""+ git.exec ["add", "FOO.TXT"]+ git.exec ["checkout", "foo.txt"]+ runLintRules git.client config defaultOptions+ lintReportSuccess report `shouldBe` False++ it "handles large number of files" . withGitRepo $ \git -> do+ forM_ [1 .. 10000 :: Int] $ \x ->+ writeFile ("test-" <> show x) ""+ git.exec ["add", "."]+ maybe (failTest "Timed out") pure <=< timeout (1 * 1000000) $ do+ report1 <- runLintRules git.client config defaultOptions+ lintReportSuccess report1 `shouldBe` True++ it "skips files failing glob" . withGitRepo $ \git -> do+ git.exec ["config", "core.ignorecase", "false"]+ writeFile "foo.txt" "" >> git.exec ["add", "foo.txt"]+ removeFile "foo.txt" >> writeFile "FOO.TXT" "" >> git.exec ["add", "FOO.TXT"] >> git.exec ["checkout", "foo.txt"]+ report <-+ runLintRules+ git.client+ (withFiles ["FOO.txt"] config)+ defaultOptions+ lintReportSuccess report `shouldBe` True++ describe "check_merge_conflict" $ do+ let config = defaultConfig LintRule_CheckMergeConflict++ it "succeeds when there are no merge conflicts" $ do+ report <-+ withGitRepo $ \git -> do+ writeFile "foo.txt" "" >> git.exec ["add", "foo.txt"] >> git.exec ["commit", "-m", "Initial commit"]+ git.exec ["switch", "-c", "branch1"] >> writeFile "foo.txt" "branch1" >> git.exec ["add", "foo.txt"] >> git.exec ["commit", "-m", "branch1"]+ git.exec ["switch", "-c", "branch2"] >> writeFile "bar.txt" "branch2" >> git.exec ["add", "bar.txt"] >> git.exec ["commit", "-m", "branch2"]+ git.exec ["switch", "main"]+ git.exec ["merge", "branch1", "branch2"]+ runLintRules git.client config defaultOptions{files = gitFiles ["foo.txt"]}+ lintReportSuccess report `shouldBe` True++ it "fails when there are merge conflicts" $ do+ report <-+ withGitRepo $ \git -> do+ writeFile "foo.txt" "" >> git.exec ["add", "foo.txt"] >> git.exec ["commit", "-m", "Initial commit"]+ git.exec ["switch", "-c", "branch1", "main"] >> writeFile "foo.txt" "branch1" >> git.exec ["add", "foo.txt"] >> git.exec ["commit", "-m", "branch1"]+ git.exec ["switch", "-c", "branch2", "main"] >> writeFile "foo.txt" "branch2" >> git.exec ["add", "foo.txt"] >> git.exec ["commit", "-m", "branch2"]+ git.exec ["switch", "main"]+ git.exec ["merge", "branch1", "branch2"] `shouldSatisfy` P.throws (P.anything @SomeException)+ runLintRules git.client config defaultOptions{files = gitFiles ["foo.txt"]}+ lintReportSuccess report `shouldBe` False+ renderLintReport report `shouldSatisfy` P.matchesSnapshot++ it "skips files failing glob" . withGitRepo $ \git -> do+ writeFile "foo.txt" "" >> git.exec ["add", "foo.txt"] >> git.exec ["commit", "-m", "Initial commit"]+ git.exec ["switch", "-c", "branch1", "main"] >> writeFile "foo.txt" "branch1" >> git.exec ["add", "foo.txt"] >> git.exec ["commit", "-m", "branch1"]+ git.exec ["switch", "-c", "branch2", "main"] >> writeFile "foo.txt" "branch2" >> git.exec ["add", "foo.txt"] >> git.exec ["commit", "-m", "branch2"]+ git.exec ["switch", "main"]+ git.exec ["merge", "branch1", "branch2"] `shouldSatisfy` P.throws (P.anything @SomeException)+ report <-+ runLintRules+ git.client+ (withFiles ["!foo.txt"] config)+ defaultOptions{files = gitFiles ["foo.txt"]}+ lintReportSuccess report `shouldBe` True++ describe "end_of_file_fixer" $ do+ let config = defaultConfig LintRule_EndOfFileFixer++ it "succeeds when all files have correct trailing newlines" $ do+ report <-+ withGitRepo $ \git -> do+ writeFile "foo.txt" "test\ntest\n"+ git.exec ["add", "foo.txt"]+ runLintRules git.client config defaultOptions{files = gitFiles ["foo.txt"]}+ lintReportSuccess report `shouldBe` True++ it "succeeds when file is empty" $ do+ report <-+ withGitRepo $ \git -> do+ writeFile "foo.txt" ""+ git.exec ["add", "foo.txt"]+ runLintRules git.client config defaultOptions{files = gitFiles ["foo.txt"]}+ lintReportSuccess report `shouldBe` True++ it "fails when file has no trailing newlines" $ do+ report <-+ withGitRepo $ \git -> do+ writeFile "foo.txt" "test\ntest"+ git.exec ["add", "foo.txt"]+ runLintRules git.client config defaultOptions{files = gitFiles ["foo.txt"]}+ lintReportSuccess report `shouldBe` False+ renderLintReport report `shouldSatisfy` P.matchesSnapshot++ it "fails when file has multiple trailing newlines" $ do+ report <-+ withGitRepo $ \git -> do+ writeFile "foo.txt" "test\ntest\n\n\n\n"+ git.exec ["add", "foo.txt"]+ runLintRules git.client config defaultOptions{files = gitFiles ["foo.txt"]}+ lintReportSuccess report `shouldBe` False++ it "autofixes when file has no trailing newlines" $ do+ report <-+ withGitRepo $ \git -> do+ writeFile "foo.txt" "test\ntest"+ git.exec ["add", "foo.txt"]+ report <- runLintRules git.client config defaultOptions{autofix = True, files = gitFiles ["foo.txt"]}+ readFile "foo.txt" `shouldSatisfy` P.returns (P.eq "test\ntest\n")+ pure report+ lintReportSuccess report `shouldBe` False+ renderLintReport report `shouldSatisfy` P.matchesSnapshot++ it "autofixes when file has multiple trailing newlines" $ do+ report <-+ withGitRepo $ \git -> do+ writeFile "foo.txt" "test\ntest\n\n\n\n"+ git.exec ["add", "foo.txt"]+ report <- runLintRules git.client config defaultOptions{autofix = True, files = gitFiles ["foo.txt"]}+ readFile "foo.txt" `shouldSatisfy` P.returns (P.eq "test\ntest\n")+ pure report+ lintReportSuccess report `shouldBe` False++ it "skips files failing glob" . withGitRepo $ \git -> do+ writeFile "foo.txt" "test\ntest" >> git.exec ["add", "foo.txt"]+ report <-+ runLintRules+ git.client+ (withFiles ["!*.txt"] config)+ defaultOptions{files = gitFiles ["foo.txt"]}+ lintReportSuccess report `shouldBe` True++ describe "no_commit_to_branch" $ do+ let mkConfig branch = withFiles [] . defaultConfig $ LintRule_NoCommitToBranch [toGlob branch]++ it "succeeds when committing on another branch" $ do+ report <-+ withGitRepo $ \git -> do+ git.exec ["switch", "-c", "test"]+ runLintRules git.client (mkConfig "main") defaultOptions+ lintReportSuccess report `shouldBe` True++ it "fails when committing on bad branch" $ do+ report <-+ withGitRepo $ \git -> do+ runLintRules git.client (mkConfig "main") defaultOptions+ lintReportSuccess report `shouldBe` False+ renderLintReport report `shouldSatisfy` P.matchesSnapshot++ it "supports globs" $ do+ report <-+ withGitRepo $ \git -> do+ git.exec ["switch", "-c", "release-2.0"]+ runLintRules git.client (mkConfig "release-*") defaultOptions+ lintReportSuccess report `shouldBe` False+ renderLintReport report `shouldSatisfy` P.matchesSnapshot++ describe "trailing_whitespace" $ do+ let config = defaultConfig LintRule_TrailingWhitespace++ it "succeeds when no lines have trailing whitespace" $ do+ report <-+ withGitRepo $ \git -> do+ writeFile "foo.txt" "test\ntest\n"+ git.exec ["add", "foo.txt"]+ runLintRules git.client config defaultOptions{files = gitFiles ["foo.txt"]}+ lintReportSuccess report `shouldBe` True++ it "fails when line has trailing whitespace" $ do+ report <-+ withGitRepo $ \git -> do+ writeFile "end-space.txt" "test \ntest\n"+ writeFile "end-tab.txt" "test\t\t\ntest\n"+ git.exec ["add", "end-space.txt", "end-tab.txt"]+ runLintRules git.client config $+ defaultOptions{files = gitFiles ["end-space.txt", "end-tab.txt"]}+ lintReportSuccess report `shouldBe` False+ renderLintReport report `shouldSatisfy` P.matchesSnapshot++ it "autofixes trailing whitespace" $ do+ report <-+ withGitRepo $ \git -> do+ writeFile "end-space.txt" "test \ntest\n"+ writeFile "end-tab.txt" "test\t\t\ntest\n"+ git.exec ["add", "end-space.txt", "end-tab.txt"]+ report <-+ runLintRules git.client config $+ defaultOptions+ { autofix = True+ , files = gitFiles ["end-space.txt", "end-tab.txt"]+ }+ readFile "end-space.txt" `shouldSatisfy` P.returns (P.eq "test\ntest\n")+ readFile "end-tab.txt" `shouldSatisfy` P.returns (P.eq "test\ntest\n")+ pure report+ lintReportSuccess report `shouldBe` False+ renderLintReport report `shouldSatisfy` P.matchesSnapshot++ it "skips files failing glob" . withGitRepo $ \git -> do+ writeFile "bad.txt" "test \ntest\n" >> git.exec ["add", "bad.txt"]+ report <-+ runLintRules+ git.client+ (withFiles ["!*.txt"] config)+ defaultOptions{files = gitFiles ["bad.txt"]}+ lintReportSuccess report `shouldBe` True++defaultOptions :: LintOptions+defaultOptions =+ LintOptions+ { autofix = False+ , files = mempty+ }++gitFiles :: [FilePath] -> Map OsPath GitFile+gitFiles paths =+ Map.fromList+ [ (path, GitFile path)+ | path <- map OsPath.fromFilePath paths+ ]++defaultConfig :: LintRuleRule -> Config+defaultConfig rule =+ Config+ { repoConfigPath = [osp|.hooky.kdl|]+ , repo =+ RepoConfig+ { fileGlobs = []+ , hooks = []+ , lintRules = [LintRule rule [toGlob "*"]]+ }+ , global = error "GlobalConfig not used"+ , skippedHooks = mempty+ }++withFiles :: [Text] -> Config -> Config+withFiles globs config =+ config+ { repo =+ config.repo+ { lintRules =+ flip map config.repo.lintRules $ \rule ->+ rule{LintRule.fileGlobs = map toGlob globs}+ }+ }
+ test/Hooky/TestUtils/Git.hs view
@@ -0,0 +1,64 @@+{-# LANGUAGE DataKinds #-}+{-# LANGUAGE OverloadedRecordDot #-}+{-# LANGUAGE OverloadedStrings #-}+{-# LANGUAGE QuasiQuotes #-}++module Hooky.TestUtils.Git (+ TestGitClient (..),+ withGitRepo,+) where++import Control.Monad (unless)+import Data.Text (Text)+import Data.Text qualified as Text+import Data.Text.IO qualified as Text+import GHC.Records (HasField (..))+import Hooky.Utils.Git (GitClient (..))+import Hooky.Utils.OsPath qualified as OsPath+import System.Directory.OsPath (+ createDirectoryIfMissing,+ withCurrentDirectory,+ )+import System.Exit (ExitCode (..))+import System.IO qualified as IO+import System.IO.Temp (withSystemTempDirectory)+import System.OsPath (OsPath, osp, (</>))+import System.Process qualified as Process++data TestGitClient = TestGitClient {repo :: OsPath}++instance HasField "client" TestGitClient GitClient where+ getField TestGitClient{repo} = GitClient{repo}++instance HasField "run" TestGitClient ([String] -> IO (ExitCode, Text, Text)) where+ getField git args = do+ log_ $ "run: " <> Text.show args+ (code, stdoutS, stderrS) <-+ flip Process.readCreateProcessWithExitCode "" $+ Process.proc "git" $+ ["-C", OsPath.toFilePath git.repo] <> args+ let (stdout, stderr) = (toText stdoutS, toText stderrS)+ unless (Text.null stdout) $ do+ log_ $ "stdout:\n" <> stdout+ unless (Text.null stderr) $ do+ log_ $ "stderr:\n" <> stderr+ pure (code, stdout, stderr)+ where+ toText = Text.strip . Text.pack+ log_ msg = Text.hPutStrLn IO.stderr $ "[TestGitClient] " <> msg++instance HasField "exec" TestGitClient ([String] -> IO ()) where+ getField git args = do+ (code, _, _) <- git.run args+ case code of+ ExitSuccess -> pure ()+ ExitFailure n -> error $ "git failed with " <> show n++withGitRepo :: (TestGitClient -> IO a) -> IO a+withGitRepo action =+ withSystemTempDirectory "git.XXXX" $ \tmpdir -> do+ let git = TestGitClient{repo = OsPath.fromFilePath tmpdir </> [osp|repo|]}+ createDirectoryIfMissing True git.repo+ withCurrentDirectory git.repo $ do+ git.exec ["init", "--initial-branch", "main"]+ action git
+ test/Hooky/TestUtils/Hooky.hs view
@@ -0,0 +1,18 @@+module Hooky.TestUtils.Hooky (+ HookyExe (..),+) where++import Skeletest+import System.Directory (findExecutable)++newtype HookyExe = HookyExe FilePath++instance Fixture HookyExe where+ fixtureScope = PerSessionFixture+ fixtureAction = do+ exe <- findExe+ pure $ noCleanup (HookyExe exe)+ where+ findExe =+ findExecutable "hooky"+ >>= maybe (error "Could not find hooky executable") pure
+ test/Hooky/Utils/GlobSpec.hs view
@@ -0,0 +1,109 @@+{-# LANGUAGE OverloadedStrings #-}++module Hooky.Utils.GlobSpec (spec) where++import Data.Text (Text)+import Data.Text qualified as Text+import Hooky.Utils.Glob (+ matchesGlob,+ matchesGlobs,+ toGlob,+ )+import Skeletest+import Skeletest.Predicate qualified as P+import Skeletest.Prop qualified as Prop+import Skeletest.Prop.Gen qualified as Gen+import Skeletest.Prop.Range qualified as Range++spec :: Spec+spec = do+ globSpec++globSpec :: Spec+globSpec = do+ describe "Glob" $ do+ describe "matchesGlob" $ do+ let+ glob `matches` input = \expected ->+ it (show glob <> " matches " <> show input <> " ==> " <> show expected) $ do+ matchesGlob (toGlob glob) input `shouldBe` expected+ (==>) = ($)++ "*" `matches` "Foo.hs" ==> True+ "*.hs" `matches` "Foo.hs" ==> True+ "*.hs" `matches` "Foo.hs.txt" ==> False+ "*.hs" `matches` "Foo/Bar.hs" ==> True+ "*.hs" `matches` "Foo/Bar.txt" ==> False+ "*.hs" `matches` "Foo/Bar.hs/Baz" ==> False+ "Foo*.hs" `matches` "Foo.hs" ==> True+ "Foo*.hs" `matches` "FooBar.hs" ==> True+ "Foo*.hs" `matches` "FooBar.hs.txt" ==> False+ "!*.hs" `matches` "Foo.hs" ==> False+ "!*.hs" `matches` "Foo/Bar.hs" ==> False+ "!*.hs" `matches` "Foo/Bar.txt" ==> True+ "!*.hs" `matches` "Foo/Bar.hs/Baz" ==> True+ "/*.hs" `matches` "Foo.hs" ==> True+ "/*.hs" `matches` "Foo/Bar.hs" ==> False+ "Foo/Bar.hs" `matches` "Foo/Bar.hs" ==> True+ "Foo/Bar.hs" `matches` "path/to/Foo/Bar.hs" ==> True+ "/Foo/Bar.hs" `matches` "Foo/Bar.hs" ==> True+ "/Foo/Bar.hs" `matches` "path/to/Foo/Bar.hs" ==> False+ "**/*.hs" `matches` "Foo.hs" ==> True+ "**/*.hs" `matches` "Foo/Bar.hs" ==> True+ "**/*.hs" `matches` "Foo/Bar/Baz.hs" ==> True+ "**/*.hs" `matches` "Foo.txt" ==> False+ "**/*.hs" `matches` "Foo/Bar/Baz.txt" ==> False+ "!**/*.hs" `matches` "Foo.hs" ==> False+ "!**/*.hs" `matches` "Foo/Bar.hs" ==> False+ "!**/*.hs" `matches` "Foo/Bar/Baz.hs" ==> False+ "!**/*.hs" `matches` "Foo.txt" ==> True+ "!**/*.hs" `matches` "Foo/Bar/Baz.txt" ==> True++ -- Brace expansion+ "{foo,bar}.{hs,txt}" `matches` "foo.hs" ==> True+ "{foo,bar}.{hs,txt}" `matches` "bar.hs" ==> True+ "{foo,bar}.{hs,txt}" `matches` "foo.txt" ==> True+ "{foo,bar}.{hs,txt}" `matches` "bar.txt" ==> True+ "!{foo,bar}.{hs,txt}" `matches` "bar.txt" ==> False+ "!{foo,bar}.{hs,txt}" `matches` "baz.txt" ==> True++ -- Hidden files/directories+ "*" `matches` ".gitignore" ==> True+ "**/*" `matches` ".foo/test" ==> True++ prop "'<path>' and '**/<path>' are equivalent" $ do+ Prop.setTestLimit 10000+ g <- forAll genRelGlob+ let g1 = toGlob g+ g2 = toGlob ("**/" <> g)+ (matchesGlob g1 P.=== matchesGlob g2) `shouldSatisfy` P.isoWith genRelPath++ describe "matchesGlobs" $ do+ let+ globs `matches` input = \expected ->+ it (show globs <> " matches " <> show input <> " ==> " <> show expected) $ do+ matchesGlobs (map toGlob globs) input `shouldBe` expected+ (==>) = ($)++ ["**/*"] `matches` "Foo.hs" ==> True+ ["!**/*.golden"] `matches` "Foo.hs" ==> True+ ["!**/*.golden", "**/*"] `matches` "Foo.hs" ==> True++ pure () -- TODO: property test where matchesGlobs [g] === matchesGlob g+ where+ genRelPathLike :: Gen Text -> Gen Text+ genRelPathLike g = Text.intercalate "/" <$> Gen.list (Range.linear 1 10) g++ genRelPath :: Gen Text+ genRelPath = genRelPathLike $ Gen.text (Range.linear 1 30) Gen.unicode++ genRelGlob :: Gen Text+ genRelGlob =+ genRelPathLike $+ fmap Text.concat . Gen.list (Range.linear 1 5) $+ Gen.frequency+ [ (9, Gen.text (Range.linear 1 5) genChar)+ , (1, pure "*")+ ]++ genChar = Gen.filter (/= '!') Gen.unicode
+ test/Hooky/__snapshots__/E2ESpec.snap.md view
@@ -0,0 +1,50 @@+# test/Hooky/E2ESpec.hs++## hooky run / outputs --format=full++```+◈─── PASS hooky_pass (duration: XX.XXXs)+╭─── FAIL hooky_fail (duration: XX.XXXs)+│ ═══▶ Running: hooky lint+│ file.fail:+│ - [end_of_file_fixer] file would be changed+◈+◈─── SKIP hooky_skip (duration: XX.XXXs)+1 hook passed ✔+1 hook failed ✘+1 hook skipped ≫+```++## hooky run / outputs --format=minimal++```+╭─── FAIL hooky_fail (duration: XX.XXXs)+│ ═══▶ Running: hooky lint+│ file.fail:+│ - [end_of_file_fixer] file would be changed+◈+1 hook passed ✔+1 hook failed ✘+1 hook skipped ≫+```++## hooky run / outputs --format=verbose++```+╭─── PASS hooky_pass (duration: XX.XXXs)+│ ═══▶ Running: hooky lint+│ Hooks passed:+│ - end_of_file_fixer+◈+╭─── FAIL hooky_fail (duration: XX.XXXs)+│ ═══▶ Running: hooky lint+│ file.fail:+│ - [end_of_file_fixer] file would be changed+◈+╭─── SKIP hooky_skip (duration: XX.XXXs)+│ ═══▶ Running: hooky lint+◈+1 hook passed ✔+1 hook failed ✘+1 hook skipped ≫+```
+ test/Hooky/__snapshots__/LintSpec.snap.md view
@@ -0,0 +1,70 @@+# Hooky.Lint++## check_broken_symlinks / fails when a symlink is broken++```+foo-link.txt:+- [check_broken_symlinks] File is a broken symlink. Remove or exclude from rule+```++## check_case_conflict / fails when files conflict++```+foo.txt:+- [check_case_conflict] File conflicts with: FOO.TXT+```++## check_merge_conflict / fails when there are merge conflicts++```+foo.txt:+- [check_merge_conflict] Merge conflict string found at line 1: "<<<<<<< "+```++## end_of_file_fixer / autofixes when file has no trailing newlines++```+foo.txt:+- [end_of_file_fixer] FIXED+```++## end_of_file_fixer / fails when file has no trailing newlines++```+foo.txt:+- [end_of_file_fixer] file would be changed+```++## no_commit_to_branch / fails when committing on bad branch++```+FAILURES:+- [no_commit_to_branch] cannot commit to branch: main+```++## no_commit_to_branch / supports globs++```+FAILURES:+- [no_commit_to_branch] cannot commit to branch: release-2.0+```++## trailing_whitespace / autofixes trailing whitespace++```+end-space.txt:+- [trailing_whitespace] FIXED++end-tab.txt:+- [trailing_whitespace] FIXED+```++## trailing_whitespace / fails when line has trailing whitespace++```+end-space.txt:+- [trailing_whitespace] file would be changed++end-tab.txt:+- [trailing_whitespace] file would be changed+```
+ test/Main.hs view
@@ -0,0 +1,1 @@+import Skeletest.Main