policeman (empty) → 0.0.0.0
raw patch · 22 files changed
+1623/−0 lines, 22 filesdep +Cabaldep +ansi-terminaldep +base
Dependencies added: Cabal, ansi-terminal, base, containers, dir-traverse, directory, filepath, ghc, gitrev, hedgehog, hspec, mtl, optparse-applicative, policeman, relude, shellmet, text, transformers, unordered-containers
Files
- CHANGELOG.md +11/−0
- LICENSE +373/−0
- README.md +99/−0
- app/Main.hs +9/−0
- policeman.cabal +122/−0
- src/Policeman.hs +13/−0
- src/Policeman/Cabal.hs +88/−0
- src/Policeman/Cli.hs +63/−0
- src/Policeman/ColorTerminal.hs +81/−0
- src/Policeman/Core/Diff.hs +37/−0
- src/Policeman/Core/Hie.hs +60/−0
- src/Policeman/Core/Package.hs +42/−0
- src/Policeman/Core/Version.hs +113/−0
- src/Policeman/Diff.hs +82/−0
- src/Policeman/Download/Common.hs +20/−0
- src/Policeman/Download/Hackage.hs +82/−0
- src/Policeman/Evaluate.hs +56/−0
- src/Policeman/Hie.hs +49/−0
- src/Policeman/Run.hs +84/−0
- test/Spec.hs +26/−0
- test/Test/Policeman/Cabal.hs +30/−0
- test/Test/Policeman/Version.hs +83/−0
+ CHANGELOG.md view
@@ -0,0 +1,11 @@+# Changelog++`policeman` uses [PVP Versioning][1].+The changelog is available [on GitHub][2].++## 0.0.0.0++* Initially created.++[1]: https://pvp.haskell.org+[2]: https://github.com/kowainik/policeman/releases
+ LICENSE view
@@ -0,0 +1,373 @@+Mozilla Public License Version 2.0+==================================++1. Definitions+--------------++1.1. "Contributor"+ means each individual or legal entity that creates, contributes to+ the creation of, or owns Covered Software.++1.2. "Contributor Version"+ means the combination of the Contributions of others (if any) used+ by a Contributor and that particular Contributor's Contribution.++1.3. "Contribution"+ means Covered Software of a particular Contributor.++1.4. "Covered Software"+ means Source Code Form to which the initial Contributor has attached+ the notice in Exhibit A, the Executable Form of such Source Code+ Form, and Modifications of such Source Code Form, in each case+ including portions thereof.++1.5. "Incompatible With Secondary Licenses"+ means++ (a) that the initial Contributor has attached the notice described+ in Exhibit B to the Covered Software; or++ (b) that the Covered Software was made available under the terms of+ version 1.1 or earlier of the License, but not also under the+ terms of a Secondary License.++1.6. "Executable Form"+ means any form of the work other than Source Code Form.++1.7. "Larger Work"+ means a work that combines Covered Software with other material, in+ a separate file or files, that is not Covered Software.++1.8. "License"+ means this document.++1.9. "Licensable"+ means having the right to grant, to the maximum extent possible,+ whether at the time of the initial grant or subsequently, any and+ all of the rights conveyed by this License.++1.10. "Modifications"+ means any of the following:++ (a) any file in Source Code Form that results from an addition to,+ deletion from, or modification of the contents of Covered+ Software; or++ (b) any new file in Source Code Form that contains any Covered+ Software.++1.11. "Patent Claims" of a Contributor+ means any patent claim(s), including without limitation, method,+ process, and apparatus claims, in any patent Licensable by such+ Contributor that would be infringed, but for the grant of the+ License, by the making, using, selling, offering for sale, having+ made, import, or transfer of either its Contributions or its+ Contributor Version.++1.12. "Secondary License"+ means either the GNU General Public License, Version 2.0, the GNU+ Lesser General Public License, Version 2.1, the GNU Affero General+ Public License, Version 3.0, or any later versions of those+ licenses.++1.13. "Source Code Form"+ means the form of the work preferred for making modifications.++1.14. "You" (or "Your")+ means an individual or a legal entity exercising rights under this+ License. For legal entities, "You" includes any entity that+ controls, is controlled by, or is under common control with You. For+ purposes of this definition, "control" means (a) the power, direct+ or indirect, to cause the direction or management of such entity,+ whether by contract or otherwise, or (b) ownership of more than+ fifty percent (50%) of the outstanding shares or beneficial+ ownership of such entity.++2. License Grants and Conditions+--------------------------------++2.1. Grants++Each Contributor hereby grants You a world-wide, royalty-free,+non-exclusive license:++(a) under intellectual property rights (other than patent or trademark)+ Licensable by such Contributor to use, reproduce, make available,+ modify, display, perform, distribute, and otherwise exploit its+ Contributions, either on an unmodified basis, with Modifications, or+ as part of a Larger Work; and++(b) under Patent Claims of such Contributor to make, use, sell, offer+ for sale, have made, import, and otherwise transfer either its+ Contributions or its Contributor Version.++2.2. Effective Date++The licenses granted in Section 2.1 with respect to any Contribution+become effective for each Contribution on the date the Contributor first+distributes such Contribution.++2.3. Limitations on Grant Scope++The licenses granted in this Section 2 are the only rights granted under+this License. No additional rights or licenses will be implied from the+distribution or licensing of Covered Software under this License.+Notwithstanding Section 2.1(b) above, no patent license is granted by a+Contributor:++(a) for any code that a Contributor has removed from Covered Software;+ or++(b) for infringements caused by: (i) Your and any other third party's+ modifications of Covered Software, or (ii) the combination of its+ Contributions with other software (except as part of its Contributor+ Version); or++(c) under Patent Claims infringed by Covered Software in the absence of+ its Contributions.++This License does not grant any rights in the trademarks, service marks,+or logos of any Contributor (except as may be necessary to comply with+the notice requirements in Section 3.4).++2.4. Subsequent Licenses++No Contributor makes additional grants as a result of Your choice to+distribute the Covered Software under a subsequent version of this+License (see Section 10.2) or under the terms of a Secondary License (if+permitted under the terms of Section 3.3).++2.5. Representation++Each Contributor represents that the Contributor believes its+Contributions are its original creation(s) or it has sufficient rights+to grant the rights to its Contributions conveyed by this License.++2.6. Fair Use++This License is not intended to limit any rights You have under+applicable copyright doctrines of fair use, fair dealing, or other+equivalents.++2.7. Conditions++Sections 3.1, 3.2, 3.3, and 3.4 are conditions of the licenses granted+in Section 2.1.++3. Responsibilities+-------------------++3.1. Distribution of Source Form++All distribution of Covered Software in Source Code Form, including any+Modifications that You create or to which You contribute, must be under+the terms of this License. You must inform recipients that the Source+Code Form of the Covered Software is governed by the terms of this+License, and how they can obtain a copy of this License. You may not+attempt to alter or restrict the recipients' rights in the Source Code+Form.++3.2. Distribution of Executable Form++If You distribute Covered Software in Executable Form then:++(a) such Covered Software must also be made available in Source Code+ Form, as described in Section 3.1, and You must inform recipients of+ the Executable Form how they can obtain a copy of such Source Code+ Form by reasonable means in a timely manner, at a charge no more+ than the cost of distribution to the recipient; and++(b) You may distribute such Executable Form under the terms of this+ License, or sublicense it under different terms, provided that the+ license for the Executable Form does not attempt to limit or alter+ the recipients' rights in the Source Code Form under this License.++3.3. Distribution of a Larger Work++You may create and distribute a Larger Work under terms of Your choice,+provided that You also comply with the requirements of this License for+the Covered Software. If the Larger Work is a combination of Covered+Software with a work governed by one or more Secondary Licenses, and the+Covered Software is not Incompatible With Secondary Licenses, this+License permits You to additionally distribute such Covered Software+under the terms of such Secondary License(s), so that the recipient of+the Larger Work may, at their option, further distribute the Covered+Software under the terms of either this License or such Secondary+License(s).++3.4. Notices++You may not remove or alter the substance of any license notices+(including copyright notices, patent notices, disclaimers of warranty,+or limitations of liability) contained within the Source Code Form of+the Covered Software, except that You may alter any license notices to+the extent required to remedy known factual inaccuracies.++3.5. Application of Additional Terms++You may choose to offer, and to charge a fee for, warranty, support,+indemnity or liability obligations to one or more recipients of Covered+Software. However, You may do so only on Your own behalf, and not on+behalf of any Contributor. You must make it absolutely clear that any+such warranty, support, indemnity, or liability obligation is offered by+You alone, and You hereby agree to indemnify every Contributor for any+liability incurred by such Contributor as a result of warranty, support,+indemnity or liability terms You offer. You may include additional+disclaimers of warranty and limitations of liability specific to any+jurisdiction.++4. Inability to Comply Due to Statute or Regulation+---------------------------------------------------++If it is impossible for You to comply with any of the terms of this+License with respect to some or all of the Covered Software due to+statute, judicial order, or regulation then You must: (a) comply with+the terms of this License to the maximum extent possible; and (b)+describe the limitations and the code they affect. Such description must+be placed in a text file included with all distributions of the Covered+Software under this License. Except to the extent prohibited by statute+or regulation, such description must be sufficiently detailed for a+recipient of ordinary skill to be able to understand it.++5. Termination+--------------++5.1. The rights granted under this License will terminate automatically+if You fail to comply with any of its terms. However, if You become+compliant, then the rights granted under this License from a particular+Contributor are reinstated (a) provisionally, unless and until such+Contributor explicitly and finally terminates Your grants, and (b) on an+ongoing basis, if such Contributor fails to notify You of the+non-compliance by some reasonable means prior to 60 days after You have+come back into compliance. Moreover, Your grants from a particular+Contributor are reinstated on an ongoing basis if such Contributor+notifies You of the non-compliance by some reasonable means, this is the+first time You have received notice of non-compliance with this License+from such Contributor, and You become compliant prior to 30 days after+Your receipt of the notice.++5.2. If You initiate litigation against any entity by asserting a patent+infringement claim (excluding declaratory judgment actions,+counter-claims, and cross-claims) alleging that a Contributor Version+directly or indirectly infringes any patent, then the rights granted to+You by any and all Contributors for the Covered Software under Section+2.1 of this License shall terminate.++5.3. In the event of termination under Sections 5.1 or 5.2 above, all+end user license agreements (excluding distributors and resellers) which+have been validly granted by You or Your distributors under this License+prior to termination shall survive termination.++************************************************************************+* *+* 6. Disclaimer of Warranty *+* ------------------------- *+* *+* Covered Software is provided under this License on an "as is" *+* basis, without warranty of any kind, either expressed, implied, or *+* statutory, including, without limitation, warranties that the *+* Covered Software is free of defects, merchantable, fit for a *+* particular purpose or non-infringing. The entire risk as to the *+* quality and performance of the Covered Software is with You. *+* Should any Covered Software prove defective in any respect, You *+* (not any Contributor) assume the cost of any necessary servicing, *+* repair, or correction. This disclaimer of warranty constitutes an *+* essential part of this License. No use of any Covered Software is *+* authorized under this License except under this disclaimer. *+* *+************************************************************************++************************************************************************+* *+* 7. Limitation of Liability *+* -------------------------- *+* *+* Under no circumstances and under no legal theory, whether tort *+* (including negligence), contract, or otherwise, shall any *+* Contributor, or anyone who distributes Covered Software as *+* permitted above, be liable to You for any direct, indirect, *+* special, incidental, or consequential damages of any character *+* including, without limitation, damages for lost profits, loss of *+* goodwill, work stoppage, computer failure or malfunction, or any *+* and all other commercial damages or losses, even if such party *+* shall have been informed of the possibility of such damages. This *+* limitation of liability shall not apply to liability for death or *+* personal injury resulting from such party's negligence to the *+* extent applicable law prohibits such limitation. Some *+* jurisdictions do not allow the exclusion or limitation of *+* incidental or consequential damages, so this exclusion and *+* limitation may not apply to You. *+* *+************************************************************************++8. Litigation+-------------++Any litigation relating to this License may be brought only in the+courts of a jurisdiction where the defendant maintains its principal+place of business and such litigation shall be governed by laws of that+jurisdiction, without reference to its conflict-of-law provisions.+Nothing in this Section shall prevent a party's ability to bring+cross-claims or counter-claims.++9. Miscellaneous+----------------++This License represents the complete agreement concerning the subject+matter hereof. If any provision of this License is held to be+unenforceable, such provision shall be reformed only to the extent+necessary to make it enforceable. Any law or regulation which provides+that the language of a contract shall be construed against the drafter+shall not be used to construe this License against a Contributor.++10. Versions of the License+---------------------------++10.1. New Versions++Mozilla Foundation is the license steward. Except as provided in Section+10.3, no one other than the license steward has the right to modify or+publish new versions of this License. Each version will be given a+distinguishing version number.++10.2. Effect of New Versions++You may distribute the Covered Software under the terms of the version+of the License under which You originally received the Covered Software,+or under the terms of any subsequent version published by the license+steward.++10.3. Modified Versions++If you create software not governed by this License, and you want to+create a new license for such software, you may create and use a+modified version of this License if you rename the license and remove+any references to the name of the license steward (except to note that+such modified license differs from this License).++10.4. Distributing Source Code Form that is Incompatible With Secondary+Licenses++If You choose to distribute Source Code Form that is Incompatible With+Secondary Licenses under the terms of this version of the License, the+notice described in Exhibit B of this License must be attached.++Exhibit A - Source Code Form License Notice+-------------------------------------------++ This Source Code Form is subject to the terms of the Mozilla Public+ License, v. 2.0. If a copy of the MPL was not distributed with this+ file, You can obtain one at http://mozilla.org/MPL/2.0/.++If it is not possible or desirable to put the notice in a particular+file, then You may include the notice in a location (such as a LICENSE+file in a relevant directory) where a recipient would be likely to look+for such a notice.++You may add additional accurate notices of copyright ownership.++Exhibit B - "Incompatible With Secondary Licenses" Notice+---------------------------------------------------------++ This Source Code Form is "Incompatible With Secondary Licenses", as+ defined by the Mozilla Public License, v. 2.0.
+ README.md view
@@ -0,0 +1,99 @@+# Policeman++++[](https://github.com/kowainik/policeman/actions)+[](https://hackage.haskell.org/package/policeman)+[](LICENSE)+++👮 Policeman is the Kowainik's+[Bristol Haskell Hackathon](https://mpickering.github.io/bristol2020.html)+project.++🏗 The current status is MVP, though it could already be used on ordinary cases.++`Policeman` assists to properly choose the next version number according to+[PVP]() (Packaging Version Policy) for the Haskell packages based on the+semantical changes to the interface.++For a better understanding of the project basis and implementation details+please refer to the following blog post:++* [Kowainik: Policeman in da city](https://kowainik.github.io/posts/policeman-bristol)++## Prerequisites++Policeman heavily uses some modern features of the Haskell compiler+[GHC](https://www.haskell.org/ghc/).+Therefore, in order to start using `Policeman` on the projects, you are required+to have the following set:++ * Global GHC version `8.8` and higher+ * Support of GHC `8.8` and higher in your current project and the version you+ wish to compare to+ * [cabal](https://www.haskell.org/cabal/) build tool version `3.0` or higher+ installed on your machine++## Installation++The initial beta version of `Policeman` is already available on Hackage.+To install it locally you need to execute the following commands:++```shell+cabal update+cabal install policeman+```++Alternatively, you can install the `Policeman` tool from the sources. For+achieving that, you have a couple of options.++First one is to fetch the repo using `cabal`:++```shell+cabal get -s policeman+```++Or, you can clone the directory directly from GitHub:++```shell+git clone https://github.com/kowainik/policeman.git+```++The next steps are identical in both option. You need to step into the+directory:++```shell+cd policeman+```++And finally, build and install the tool using `cabal`:++```shell+cabal install policeman:exe:policeman+```++## How to use++By default, Policeman aims to compare your local version with the latest+available Hackage version of the package. It grabs the information about your+package automatically, so no need to provide that. That means that the simplest+command looks like this:++```shell+policeman+```++It will output the suggested new version (if applicable) based on your local+changes compared to the Hackage version.++Alternatively, you can provide the Hackage version you are willing to compare+against. For that purpose, you can use `-p | --previous` option. For example:++```shell+policeman --previous "0.1.0.0"+```++## Acknowledgement++Icons made by [Freepik](http://www.freepik.com) from [www.flaticon.com](https://www.flaticon.com/) is licensed by [CC 3.0 BY](http://creativecommons.org/licenses/by/3.0/).
+ app/Main.hs view
@@ -0,0 +1,9 @@+module Main (main) where++import System.IO (hSetEncoding, utf8)++import Policeman (policeman)+++main :: IO ()+main = hSetEncoding stdout utf8 >> policeman
+ policeman.cabal view
@@ -0,0 +1,122 @@+cabal-version: 2.4+name: policeman+version: 0.0.0.0+synopsis: Haskell PVP version adviser+description:+ Policeman assists to properly choose the next version number+ according to PVP (Packaging Version Policy) for the Haskell packages based on+ the semantical changes to the interface.+homepage: https://github.com/kowainik/policeman+bug-reports: https://github.com/kowainik/policeman/issues+license: MPL-2.0+license-file: LICENSE+author: Kowainik+maintainer: Kowainik <xrom.xkov@gmail.com>+copyright: 2020 Kowainik+category: PVP, Package Management, Cabal, Development+build-type: Simple+extra-doc-files: README.md+ , CHANGELOG.md+tested-with: GHC == 8.8.1++source-repository head+ type: git+ location: https://github.com/kowainik/policeman.git++common common-options+ build-depends: base ^>= 4.13.0.0+ , relude ^>= 0.6.0.0++ mixins: base hiding (Prelude)+ , relude (Relude as Prelude)++ ghc-options: -Wall+ -Wincomplete-uni-patterns+ -Wincomplete-record-updates+ -Wcompat+ -Widentities+ -Wredundant-constraints+ -Wmissing-export-lists+ -Wpartial-fields+ -Wmissing-deriving-strategies+ -fhide-source-paths++ default-language: Haskell2010+ default-extensions: ConstraintKinds+ DeriveGeneric+ DerivingStrategies+ GeneralizedNewtypeDeriving+ InstanceSigs+ KindSignatures+ LambdaCase+ OverloadedStrings+ RecordWildCards+ ScopedTypeVariables+ StandaloneDeriving+ TupleSections+ TypeApplications+ ViewPatterns++library+ import: common-options+ hs-source-dirs: src+ exposed-modules: Policeman+ Policeman.Cabal+ Policeman.Cli+ Policeman.ColorTerminal+ Policeman.Core.Diff+ Policeman.Core.Hie+ Policeman.Core.Package+ Policeman.Core.Version+ Policeman.Diff+ -- downloading+ Policeman.Download.Common+ Policeman.Download.Hackage++ Policeman.Evaluate+ Policeman.Hie+ Policeman.Run++ autogen-modules: Paths_policeman+ other-modules: Paths_policeman++ build-depends: ansi-terminal ^>= 0.10+ , Cabal ^>= 3.0.0.0+ , containers ^>= 0.6.2+ , dir-traverse ^>= 0.2.2.2+ , directory ^>= 1.3+ , filepath ^>= 1.4+ , ghc ^>= 8.8+ , gitrev ^>= 1.3+ , mtl ^>= 2.2.2+ , optparse-applicative ^>= 0.15+ , shellmet ^>= 0.0.3.0+ , text ^>= 1.2.4+ , transformers ^>= 0.5.6+ , unordered-containers ^>= 0.2.10++executable policeman+ import: common-options+ hs-source-dirs: app+ main-is: Main.hs+ build-depends: policeman++test-suite policeman-test+ import: common-options+ type: exitcode-stdio-1.0+ hs-source-dirs: test+ main-is: Spec.hs+ other-modules: Test.Policeman.Cabal+ Test.Policeman.Version++ build-depends: Cabal ^>= 3.0.0.0+ , directory ^>= 1.3+ , filepath ^>= 1.4+ , hedgehog ^>= 1.0+ , hspec ^>= 2.7.1+ , policeman+ , text++ ghc-options: -threaded+ -rtsopts+ -with-rtsopts=-N
+ src/Policeman.hs view
@@ -0,0 +1,13 @@+module Policeman+ ( policeman+ ) where++import Options.Applicative (execParser)++import Policeman.Cli (policemanParser)+import Policeman.Run (runPoliceman)+++-- | Main tool exec function.+policeman :: IO ()+policeman = execParser policemanParser >>= runPoliceman
+ src/Policeman/Cabal.hs view
@@ -0,0 +1,88 @@+{- | Functions to work with Cabal file and its content.+-}++module Policeman.Cabal+ ( CabalError (..)+ , parseCabalFile+ , findCabalDescription+ , extractExposedModules+ , extractPackageName+ , extractPackageVersion+ ) where++import Control.Monad.Except (throwError)+import Distribution.ModuleName (ModuleName, components)+import Distribution.PackageDescription (CondTree (..), GenericPackageDescription (..), Library (..),+ PackageDescription (..))+import Distribution.PackageDescription.Parsec (parseGenericPackageDescriptionMaybe)+import Distribution.Types.PackageId (PackageIdentifier (..))+import Distribution.Types.Version (versionNumbers)+import System.Directory (doesDirectoryExist, listDirectory)+import System.FilePath (takeExtension, (</>))++import Policeman.Core.Package (Module (..), PackageName (..))+import Policeman.Core.Version (Version, versionFromIntList)++import qualified Distribution.Types.PackageName as Cabal+++{- | Errors about dealing with @.cabal@ files.+-}+data CabalError+ -- | Directory where we're looking for cabal file, not found.+ = NoSuchDirectory FilePath+ -- | No @.cabal@ file under given path.+ | NoCabalFile FilePath+ -- | Multiple cabal files found.+ | MultipleCabalFiles (NonEmpty FilePath)+ -- | Error parsing cabal file.+ | CabalParseError+ deriving stock (Show, Eq)++{- | This function takes a path to a directory, finds a cabal file+under this directory, parses it and returns parsed content.+-}+findCabalDescription :: FilePath -> ExceptT CabalError IO GenericPackageDescription+findCabalDescription dirPath = do+ unlessM (liftIO $ doesDirectoryExist dirPath) $ throwError $ NoSuchDirectory dirPath+ dirContent <- liftIO $ listDirectory dirPath+ let cabalFiles = filter (\p -> takeExtension p == ".cabal") dirContent+ case cabalFiles of+ [] -> throwError $ NoCabalFile dirPath+ [cabalFile] -> do+ let cabalPath = dirPath </> cabalFile+ cabalContent <- readFileBS cabalPath+ parseCabalFile cabalContent+ x:xs -> throwError $ MultipleCabalFiles (x :| xs)++-- | Parses the given cabal file source and returns 'GenericPackageDescription'+parseCabalFile :: ByteString -> ExceptT CabalError IO GenericPackageDescription+parseCabalFile cabalContent = whenNothing (parseGenericPackageDescriptionMaybe cabalContent) $+ throwError CabalParseError -- TODO: better error++extractPackageName :: GenericPackageDescription -> PackageName+extractPackageName =+ PackageName+ . toText+ . Cabal.unPackageName+ . pkgName+ . package+ . packageDescription++extractPackageVersion :: GenericPackageDescription -> Maybe Version+extractPackageVersion =+ versionFromIntList+ . versionNumbers+ . pkgVersion+ . package+ . packageDescription++extractExposedModules :: GenericPackageDescription -> [Module]+extractExposedModules =+ map toModule+ . concatMap (exposedModules . condTreeData)+ . maybeToList+ . condLibrary+ where+ toModule :: ModuleName -> Module+ toModule = Module . toText . intercalate "." . components
+ src/Policeman/Cli.hs view
@@ -0,0 +1,63 @@+{-# LANGUAGE ApplicativeDo #-}+{-# LANGUAGE TemplateHaskell #-}++{- | Command line interface for @policeman@ executable.+-}++module Policeman.Cli+ ( CliArgs (..)+ , policemanParser+ ) where++import Data.Version (showVersion)+import Development.GitRev (gitCommitDate, gitHash)+import Options.Applicative (Parser, ParserInfo, fullDesc, help, helper, info, infoOption, long,+ long, metavar, progDesc, short, strOption)++import Policeman.ColorTerminal (blueCode, boldCode, resetCode)++import qualified Paths_policeman as Meta (version)+++newtype CliArgs = CliArgs+ { cliArgsPrev :: Maybe Text -- ^ Optional previous version to compare with+ }++-- | Main parser of the @policeman@ command line tool.+policemanParser :: ParserInfo CliArgs+policemanParser = info (helper <*> versionP <*> policemanP) $+ fullDesc <> progDesc "Haskell PVP Version Adviser"++policemanP :: Parser CliArgs+policemanP = do+ cliArgsPrev <- optional hackageVersionP+ pure CliArgs{..}++hackageVersionP :: Parser Text+hackageVersionP = strOption+ $ long "previous"+ <> short 'p'+ <> metavar "VERSION"+ <> help "Previous version of the package to compare to"++-- | Show the version of the tool.+versionP :: Parser (a -> a)+versionP = infoOption policemanVersion+ $ long "version"+ <> short 'v'+ <> help "Show Policeman's badge number"++policemanVersion :: String+policemanVersion = toString $ intercalate "\n"+ [ sVersion+ , sHash+ , sDate+ ]+ where+ sVersion, sHash, sDate :: String+ sVersion = blueCode <> boldCode+ <> "👮 Policeman " <> "v" <> showVersion Meta.version <> resetCode+ sHash = " ➤ " <> blueCode <> boldCode+ <> "Git revision: " <> resetCode <> $(gitHash)+ sDate = " ➤ " <> blueCode <> boldCode+ <> "Commit date: " <> resetCode <> $(gitCommitDate)
+ src/Policeman/ColorTerminal.hs view
@@ -0,0 +1,81 @@+-- | This module contains functions for colorful printing into terminal.++module Policeman.ColorTerminal+ ( Color (..)+ , putStrFlush+ , beautyPrint+ , boldCode+ , blueCode+ , bold+ , boldText+ , boldDefault+ , italic+ , redCode+ , reset+ , resetCode+ , setColor+ , successMessage+ , warningMessage+ , errorMessage+ , infoMessage+ , skipMessage+ ) where++import System.Console.ANSI (Color (..), ColorIntensity (Vivid), ConsoleIntensity (BoldIntensity),+ ConsoleLayer (Foreground), SGR (..), setSGR, setSGRCode)+import System.IO (hFlush)+++-- | Explicit flush ensures prompt messages are in the correct order on all systems.+putStrFlush :: Text -> IO ()+putStrFlush msg = do+ putText msg+ hFlush stdout++setColor :: Color -> IO ()+setColor color = setSGR [SetColor Foreground Vivid color]++-- | Starts bold printing.+bold :: IO ()+bold = setSGR [SetConsoleIntensity BoldIntensity]++italic :: IO ()+italic = setSGR [SetItalicized True]++-- | Resets all previous settings.+reset :: IO ()+reset = do+ setSGR [Reset]+ hFlush stdout++-- | Takes list of formatting options, prints text using this format options.+beautyPrint :: [IO ()] -> Text -> IO ()+beautyPrint formats msg = do+ sequence_ formats+ putText msg+ reset++boldText :: Text -> IO ()+boldText message = bold >> putStrFlush message >> reset++boldDefault :: Text -> IO ()+boldDefault message = boldText (" [" <> message <> "]")++colorMessage :: Color -> Text -> IO ()+colorMessage color message = do+ setColor color+ putTextLn $ " " <> message+ reset++errorMessage, warningMessage, successMessage, infoMessage, skipMessage :: Text -> IO ()+errorMessage = colorMessage Red+warningMessage = colorMessage Yellow+successMessage = colorMessage Green+infoMessage = colorMessage Blue+skipMessage = colorMessage Cyan++blueCode, boldCode, redCode, resetCode :: String+redCode = setSGRCode [SetColor Foreground Vivid Red]+blueCode = setSGRCode [SetColor Foreground Vivid Blue]+boldCode = setSGRCode [SetConsoleIntensity BoldIntensity]+resetCode = setSGRCode [Reset]
+ src/Policeman/Core/Diff.hs view
@@ -0,0 +1,37 @@+{- |+-}++module Policeman.Core.Diff+ ( PackageDiff (..)+ , Diff (..)+ , emptyDiff+ , hasDiffAdded+ , hasDiffDeleted+ ) where++import Policeman.Core.Package (Export, Module)++import qualified Data.Set as Set+++data PackageDiff = PackageDiff+ { pdModule :: !(Diff Module)+ , pdExport :: !(HashMap Module (Diff Export))+ }++data Diff a = Diff+ { diffAdded :: !(Set a)+ , diffDeleted :: !(Set a)+ } deriving stock (Eq)++emptyDiff :: Diff a+emptyDiff = Diff+ { diffAdded = Set.empty+ , diffDeleted = Set.empty+ }++hasDiffDeleted :: Diff a -> Bool+hasDiffDeleted = not . Set.null . diffDeleted++hasDiffAdded :: Diff a -> Bool+hasDiffAdded = not . Set.null . diffAdded
+ src/Policeman/Core/Hie.hs view
@@ -0,0 +1,60 @@+{- | The module contains pure function to parse GHC data types that we get from+@.hie@ files.++-}+module Policeman.Core.Hie+ ( hieFileToModuleStructure+ , hieFilesToHashMap+ ) where++import Avail (AvailInfo (..))+import FastString (unpackFS)+import FieldLabel (FieldLabel, FieldLbl (..))+import HieTypes (HieFile (..))+import Module (moduleName, moduleNameString)+import Name (Name, nameOccName)+import OccName (occNameString)++import Policeman.Core.Package (Export (..), Module (..), ModuleStructure (..))++import qualified Data.HashMap.Strict as HM+import qualified Data.Set as Set+++{- | Creates the list of 'Export's from the given 'AvailInfo'.++As the data type or type class can bring to export more than 1 entry+'availInfoToExport' returns the list of the exports. It adds the name of the+data type or the type class as the prefix separated with the dot @.@.+-}+availInfoToExport :: AvailInfo -> [Export]+availInfoToExport (Avail name) = [ExportedFunction $ nameToText name]+availInfoToExport (AvailTC (nameToText -> name) pieces fields) =+ ExportedType name+ : map piecesToExport pieces+ ++ map fieldsToExport fields+ where+ piecesToExport :: Name -> Export+ piecesToExport = addPrefixName . nameToText++ fieldsToExport :: FieldLabel -> Export+ fieldsToExport FieldLabel{..} = addPrefixName $ toText $ unpackFS flLabel++ addPrefixName :: Text -> Export+ addPrefixName n = ExportedType $ name <> "." <> n++nameToText :: Name -> Text+nameToText = toText . occNameString . nameOccName+++hieFileToModuleStructure :: HieFile -> ModuleStructure+hieFileToModuleStructure hf = ModuleStructure+ { msExports = Set.fromList $ concatMap availInfoToExport $ hie_exports hf+ }+++hieFileToModule :: HieFile -> Module+hieFileToModule = Module . toText . moduleNameString . moduleName . hie_module++hieFilesToHashMap :: [HieFile] -> HashMap Module ModuleStructure+hieFilesToHashMap = HM.fromList . map (\hf -> (hieFileToModule hf, hieFileToModuleStructure hf))
+ src/Policeman/Core/Package.hs view
@@ -0,0 +1,42 @@+{- | Package metadata.+-}++module Policeman.Core.Package+ ( PackageName (..)++ -- * Package Structure+ , PackageStructure (..)+ , Export (..)+ -- ** Modules+ , Module (..)+ , ModuleStructure (..)+ ) where+++{- | Package name, like @relude@.+-}+newtype PackageName = PackageName+ { unPackageName :: Text+ } deriving newtype (Show)++{- | Overall structure of the package.+Generally speaking, this is the resulting data type of custom parsing the+project by @policeman@.+-}+data PackageStructure = PackageStructure+ { psModules :: !(Set Module) -- ^ List of the exposed modules+ , psModulesMap :: !(HashMap Module ModuleStructure) -- ^ The pairs of the module and its parsed structure.+ }++newtype Module = Module+ { unModule :: Text+ } deriving newtype (Show, Eq, Ord, Hashable)++data Export+ = ExportedFunction Text+ | ExportedType Text+ deriving stock (Show, Eq, Ord)++newtype ModuleStructure = ModuleStructure+ { msExports :: Set Export -- ^ The summary list of the exported stuff.+ }
+ src/Policeman/Core/Version.hs view
@@ -0,0 +1,113 @@+{- | Module for 'Version' data type and helper functions to work with the+PVP-agreed versioning.++More information about PVP: <https://pvp.haskell.org/>.+-}++module Policeman.Core.Version+ ( Version (..)+ -- ** Parse/Display helpers+ , versionToText+ , versionFromText+ , versionToIntList+ , versionFromIntList+ -- ** Bumping versions+ , bumpMarketingMajorVersion+ , bumpMajorVersion+ , bumpMinorVersion+ , bumpTinyMinorVersion++ ) where++import qualified Data.Text as Text+++{- | Package version that should satisfy the PVP.+-}+data Version = Version+ { versionA :: !Int -- ^ Marketing major.+ , versionB :: !Int -- ^ Major.+ , versionC :: !Int -- ^ Minor.+ , versionD :: !Int -- ^ Tiny minor.+ , versionText :: !Text -- ^ Original text version.+ } deriving stock (Eq, Show)++-- | Initial minimal PVP-satisfactory version: @0.0.0.0@.+nullVersion :: Version+nullVersion = Version+ { versionA = 0+ , versionB = 0+ , versionC = 0+ , versionD = 0+ , versionText = ""+ }++{- | Shows 'Version' in the standard format:++@+A.B.C.D+1.0.2.1+@+-}+versionToText :: Version -> Text+versionToText Version{..} = Text.intercalate "." $ map show+ [ versionA+ , versionB+ , versionC+ , versionD+ ]++versionFromText :: Text -> Maybe Version+versionFromText (Text.strip -> txt) = maybeInts >>= \ints ->+ if length ints > 4+ then Nothing+ else (\ver -> ver{versionText = txt}) <$> versionFromIntList ints+ where+ maybeInts :: Maybe [Int]+ maybeInts = mapM (readMaybe @Int . toString) $ Text.split (== '.') txt++versionToIntList :: Version -> [Int]+versionToIntList Version{..} =+ [ versionA+ , versionB+ , versionC+ , versionD+ ]++-- TODO: check on negative numbers+versionFromIntList :: [Int] -> Maybe Version+versionFromIntList [] = Nothing+versionFromIntList l@(x:xs) = Just $ mkVer x (toTriple xs)+ where+ mkVer :: Int -> (Int, Int, Int) -> Version+ mkVer versionA (versionB, versionC, versionD) = Version+ { versionText = Text.intercalate "." $ map show l+ , ..+ }++ toTriple :: [Int] -> (Int, Int, Int)+ toTriple (a:b:c:_rest) = (a, b, c)+ toTriple [a, b] = (a, b, 0)+ toTriple [a] = (a, 0, 0)+ toTriple [] = (0, 0, 0)++bumpMarketingMajorVersion :: Version -> Version+bumpMarketingMajorVersion Version{..} = nullVersion+ { versionA = versionA + 1 }++bumpMajorVersion :: Version -> Version+bumpMajorVersion Version{..} = nullVersion+ { versionA = versionA+ , versionB = versionB + 1+ }++bumpMinorVersion :: Version -> Version+bumpMinorVersion Version{..} = nullVersion+ { versionA = versionA+ , versionB = versionB+ , versionC = versionC + 1+ }++bumpTinyMinorVersion :: Version -> Version+bumpTinyMinorVersion ver@Version{..} = ver+ { versionD = versionD + 1 }
+ src/Policeman/Diff.hs view
@@ -0,0 +1,82 @@+module Policeman.Diff+ ( comparePackageStructures+ , prettyPrintDiff+ ) where++import Data.Set ((\\))++import Policeman.ColorTerminal (boldText, errorMessage, infoMessage, skipMessage, successMessage)+import Policeman.Core.Diff (Diff (..), PackageDiff (..), emptyDiff, hasDiffAdded, hasDiffDeleted)+import Policeman.Core.Package (Export, Module (..), ModuleStructure (..), PackageStructure (..))+import Policeman.Core.Version (Version, versionToText)+import Policeman.Evaluate (Evaluation (..))++import qualified Data.HashMap.Strict as HM+++{- | Compares the structure of the previous version with the current one.+Returns the `PackageDiff` between them.+-}+comparePackageStructures :: PackageStructure -> PackageStructure -> PackageDiff+comparePackageStructures psPrev psCur = PackageDiff {..}+ where+ setAddedRemoved :: (Ord a) => Set a -> Set a -> Diff a+ setAddedRemoved x y = Diff+ { diffAdded = y \\ x+ , diffDeleted = x \\ y+ }++ pdModule :: Diff Module+ pdModule = setAddedRemoved (psModules psPrev) (psModules psCur)++ pdExport :: HashMap Module (Diff Export)+ pdExport = foldl' go HM.empty oldModules+ where+ go :: HashMap Module (Diff Export) -> (Module, ModuleStructure) -> HashMap Module (Diff Export)+ go hm (modul, msPrev) = case HM.lookup modul (psModulesMap psCur) of+ Just msCur -> HM.insert modul (moduleDiffExport msPrev msCur) hm+ Nothing -> hm++ oldModules :: [(Module, ModuleStructure)]+ oldModules = HM.toList $ psModulesMap psPrev++ moduleDiffExport :: ModuleStructure -> ModuleStructure -> Diff Export+ moduleDiffExport msPrev msCur = setAddedRemoved (msExports msPrev) (msExports msCur)++{- | This function takes previous version of package, diff evaluation+result, the diff itself, and prints new suggested version based on+diff and evaluation.+-}+prettyPrintDiff :: Version -> Evaluation -> PackageDiff -> IO ()+prettyPrintDiff prevVersion Evaluation{..} PackageDiff{..} = do+ when (hasDiffDeleted pdModule) $ do+ errorMessage "Deleted modules:"+ printModule $ diffDeleted pdModule++ when (hasDiffAdded pdModule) $ do+ successMessage "New modules:"+ printModule $ diffAdded pdModule++ infoMessage "Per module diff:"+ forM_ (HM.toList pdExport) $ \(moduleName, diff@Diff{..}) ->+ when (diff /= emptyDiff) $ do+ skipMessage $ " * " <> unModule moduleName++ when (hasDiffDeleted diff) $ do+ errorMessage " Deleted exports:"+ printExport diffDeleted++ when (hasDiffAdded diff) $ do+ successMessage " Added exports:"+ printExport diffAdded++ putTextLn ""+ putText "🔄 Type of change: " *> boldText (show evaluationChange <> "\n")+ putTextLn $ "👵 Previous version: " <> versionToText prevVersion+ putTextLn $ "💎 Suggested new version: " <> versionToText evaluationVersion+ where+ printModule :: Set Module -> IO ()+ printModule = mapM_ (putTextLn . (" " <>) . unModule)++ printExport :: Set Export -> IO ()+ printExport = mapM_ (putTextLn . (" " <> ) . show)
+ src/Policeman/Download/Common.hs view
@@ -0,0 +1,20 @@+{- | Common utilities for downloading.+-}++module Policeman.Download.Common+ ( DownloadError (..)+ , evidenceDir+ ) where++import System.IO.Error (IOError)++import Policeman.Core.Package (PackageName (..))+++data DownloadError+ = NoSuchPackage PackageName+ | SystemError IOError+ deriving stock (Show)++evidenceDir :: FilePath+evidenceDir = ".policeman-evidence"
+ src/Policeman/Download/Hackage.hs view
@@ -0,0 +1,82 @@+{- | Functions to download Haskell packages from Hackage.+-}++module Policeman.Download.Hackage+ ( PackageName (..)+ , downloadFromHackage+ , getLatestHackageCabalFileContent+ ) where++import Control.Exception (catch)+import Control.Monad.Trans.Except (withExceptT)+import Shellmet (($?), ($|))+import System.Directory (createDirectoryIfMissing, getCurrentDirectory, removeDirectoryRecursive)+import System.FilePath ((</>))+import System.IO.Error (IOError, isDoesNotExistError)++import Policeman.Core.Package (PackageName (..))+import Policeman.Core.Version (Version (versionText))+import Policeman.Download.Common (DownloadError (..), evidenceDir)+++{- | By the given pacakge name it downloads the latest `.cabal` file and+returns its content.++<http://hackage.haskell.org/package/<name>/<name>.cabal>+-}+getLatestHackageCabalFileContent+ :: PackageName+ -> ExceptT DownloadError IO ByteString+getLatestHackageCabalFileContent package@(PackageName packageName) = ExceptT $+ (Right . encodeUtf8 <$> ("curl" $| ["--silent", url]))+ $? pure (Left $ NoSuchPackage package)+ where+ url :: Text+ url = mconcat+ [ hackageUrl+ , packageName+ , "/"+ , packageName+ , ".cabal"+ ]++{- | This function takes 'PackageName' and previous package+'Version', downloads @.tar.gz@ archive from Hackage and unpacks it in+the current directory.+-}+downloadFromHackage :: PackageName -> Version -> ExceptT DownloadError IO FilePath+downloadFromHackage packageName@(PackageName name) (versionText -> version) = do+ let fullName = name <> "-" <> version+ let tarName = fullName <> ".tar.gz"+ let tarUrl = mconcat+ [ hackageUrl+ , name+ , "/"+ , tarName+ ]++ let tarPath = toText $ evidenceDir </> toString tarName+ let srcPath = evidenceDir </> toString fullName+ liftIO $ createDirectoryIfMissing True evidenceDir+ withExceptT SystemError $ removeDirIfExists srcPath++ -- download archive from Hackage+ ExceptT $+ (Right <$> "curl" ["--silent", tarUrl, "--output", tarPath])+ $? pure (Left $ NoSuchPackage packageName)++ -- unpack+ liftIO $ "tar" ["-xf", tarPath, "-C", toText evidenceDir]+ liftIO $ fmap (</> srcPath) getCurrentDirectory++hackageUrl :: Text+hackageUrl = "http://hackage.haskell.org/package/"++removeDirIfExists :: FilePath -> ExceptT IOError IO ()+removeDirIfExists fileName = ExceptT $+ (Right <$> removeDirectoryRecursive fileName) `catch` (pure . handleExists)+ where+ handleExists :: IOError -> Either IOError ()+ handleExists e+ | isDoesNotExistError e = Right ()+ | otherwise = Left e
+ src/Policeman/Evaluate.hs view
@@ -0,0 +1,56 @@+{- | This is the evaluation step.++We now need to calculate the next version based on the given 'PackageDiff' and+modify the previous version accordingly.+-}+module Policeman.Evaluate+ ( ChangeType (..)+ , Evaluation (..)+ , eval+ ) where++import Policeman.Core.Diff (PackageDiff (..), emptyDiff, hasDiffAdded, hasDiffDeleted)+import Policeman.Core.Version (Version, bumpMajorVersion, bumpMinorVersion)+++{- | Defines whether a change is breaking or non-breaking or not needed at all.+-}+data ChangeType+ = NoChange+ | Minor+ | Major+ deriving stock (Show)++{- | Result of package evaluation: new version with the change type.+-}+data Evaluation = Evaluation+ { evaluationChange :: !ChangeType+ , evaluationVersion :: !Version+ }++majorChange :: Version -> Evaluation+majorChange = Evaluation Major . bumpMajorVersion++minorChange :: Version -> Evaluation+minorChange = Evaluation Minor . bumpMinorVersion++noChange :: Version -> Evaluation+noChange = Evaluation NoChange++{- | Generates the next version in agreement with PVP.+-}+eval :: Version -> PackageDiff -> Evaluation+eval ver PackageDiff{..}+ | moduleDiffNonEmpty = majorChange ver+ | removedExport = majorChange ver+ | newExport = minorChange ver+ | otherwise = noChange ver+ where+ moduleDiffNonEmpty :: Bool+ moduleDiffNonEmpty = pdModule /= emptyDiff++ removedExport :: Bool+ removedExport = any hasDiffDeleted pdExport++ newExport :: Bool+ newExport = any hasDiffAdded pdExport
+ src/Policeman/Hie.hs view
@@ -0,0 +1,49 @@+module Policeman.Hie+ ( createHieFiles+ , readHieFiles+ ) where++import HieBin (HieFileResult (hie_file_result), readHieFile)+import HieTypes (HieFile)+import NameCache (NameCache, initNameCache)+import Shellmet ()+import System.Directory (doesFileExist, getCurrentDirectory, setCurrentDirectory)+import System.Directory.Recursive (getDirRecursive)+import System.FilePath ((</>))+import UniqSupply (mkSplitUniqSupply)+++{- | Generates HIE files for the project in the given folder and+returns their parsed content. The generated files are going to be+created in the @.hie/@ folder inside the given directory.+-}+createHieFiles :: FilePath -> IO [HieFile]+createHieFiles projectDir = do+ curDir <- getCurrentDirectory+ setCurrentDirectory projectDir+ "cabal" ["clean"]+ "cabal"+ [ "v2-build"+ , "--ghc-options=-fwrite-ide-info"+ , "--ghc-options=-hiedir=.hie"+ , "--verbose=0"+ ]+ readHieFiles <* setCurrentDirectory curDir++{- | Returns content of all @.hie@ files recursively in the current+directory from the @.hie/@ folder.+-}+readHieFiles :: IO [HieFile]+readHieFiles = do+ hieDir <- (</> ".hie") <$> getCurrentDirectory+ nameCache <- createNameCache+ hieContent <- getDirRecursive hieDir+ hieFiles <- filterM doesFileExist hieContent+ forM hieFiles $ \hiePath -> do+ (hieFileResult, _newCache) <- readHieFile nameCache hiePath+ pure $ hie_file_result hieFileResult++createNameCache :: IO NameCache+createNameCache = do+ uniqSupply <- mkSplitUniqSupply 'z'+ pure $ initNameCache uniqSupply []
+ src/Policeman/Run.hs view
@@ -0,0 +1,84 @@+module Policeman.Run+ ( runPoliceman+ ) where++import Control.Monad.Except (throwError)+import Control.Monad.Trans.Except (withExceptT)+import System.Directory (getCurrentDirectory)++import Policeman.Cabal (CabalError (..), extractExposedModules, extractPackageName,+ extractPackageVersion, findCabalDescription, parseCabalFile)+import Policeman.Cli (CliArgs (..))+import Policeman.Core.Hie (hieFilesToHashMap)+import Policeman.Core.Package (Module, PackageName (..), PackageStructure (..))+import Policeman.Core.Version (Version, versionFromText)+import Policeman.Diff (comparePackageStructures, prettyPrintDiff)+import Policeman.Download.Common (DownloadError)+import Policeman.Download.Hackage (downloadFromHackage, getLatestHackageCabalFileContent)+import Policeman.Evaluate (eval)+import Policeman.Hie (createHieFiles)++import qualified Data.Set as Set+++data PolicemanError+ = DError DownloadError+ | CError CabalError+ deriving stock (Show)++-- | Runs the tool based on the CLI input.+runPoliceman :: CliArgs -> IO ()+runPoliceman CliArgs{..} = whenLeftM_ (runExceptT findNextVersion) print+ where+ findNextVersion :: ExceptT PolicemanError IO ()+ findNextVersion = do+ curPackagePath <- liftIO getCurrentDirectory+ (packageName, curModules) <- getPackageInfo curPackagePath++ let runDiff :: Version -> ExceptT PolicemanError IO ()+ runDiff prevVer = diffWith prevVer packageName curModules++ -- TODO: check for invalid version separately+ case cliArgsPrev >>= versionFromText of+ Nothing -> getLatestHackageVersion packageName >>= runDiff+ Just prev -> runDiff prev++getLatestHackageVersion :: PackageName -> ExceptT PolicemanError IO Version+getLatestHackageVersion packageName = do+ cabalContent <- withExceptT DError $ getLatestHackageCabalFileContent packageName+ packageDesc <- withExceptT CError $ parseCabalFile cabalContent+ whenNothing (extractPackageVersion packageDesc) $+ throwError $ CError CabalParseError++diffWith+ :: Version+ -> PackageName+ -> [Module]+ -> ExceptT PolicemanError IO ()+diffWith prevVersion packageName curModules = do+ prevPackagePath <- withExceptT DError $ downloadFromHackage packageName prevVersion+ (_, prevModules) <- getPackageInfo prevPackagePath++ prevHieFiles <- liftIO $ createHieFiles prevPackagePath+ curHieFiles <- liftIO $ createHieFiles "."++ let prevPackageStructure = PackageStructure+ { psModules = Set.fromList prevModules+ , psModulesMap = hieFilesToHashMap prevHieFiles+ }++ let curPackageStructure = PackageStructure+ { psModules = Set.fromList curModules+ , psModulesMap = hieFilesToHashMap curHieFiles+ }++ let diff = comparePackageStructures prevPackageStructure curPackageStructure+ let evaluation = eval prevVersion diff+ liftIO $ prettyPrintDiff prevVersion evaluation diff++getPackageInfo :: FilePath -> ExceptT PolicemanError IO (PackageName, [Module])+getPackageInfo path = withExceptT CError $ do+ packageDesc <- findCabalDescription path+ let name = extractPackageName packageDesc+ let modules = extractExposedModules packageDesc+ pure (name, modules)
+ test/Spec.hs view
@@ -0,0 +1,26 @@+module Main (main) where++import Hedgehog (Group (..), checkParallel)+import Test.Hspec (describe, hspec)++import Test.Policeman.Cabal (cabalSpec)+import Test.Policeman.Version (versionRoundtripInts, versionRoundtripText, versionSpec)+++main :: IO ()+main = do+ hspec $ describe "Policeman" $ do+ cabalSpec+ versionSpec++ -- property tests+ checkParallel hedgehogTests >>= \p -> if p then exitSuccess else exitFailure++hedgehogTests :: Group+hedgehogTests = Group "Roundtrip properties"+ [ versionRoundtripText `named` "versionFromText . versionToText ≡ Just"+ , versionRoundtripInts `named` "versionFromIntList . versionToIntList ≡ Just"+ ]+ where+ named :: a -> b -> (b, a)+ named = flip (,)
+ test/Test/Policeman/Cabal.hs view
@@ -0,0 +1,30 @@+{- | Unit tests for the cabal spec+-}++module Test.Policeman.Cabal+ ( cabalSpec+ ) where++import Distribution.PackageDescription (GenericPackageDescription)+import System.Directory (getCurrentDirectory)+import System.FilePath ((</>))+import Test.Hspec (Spec, describe, it, runIO, shouldReturn, shouldSatisfy)++import Policeman.Cabal (CabalError (..), findCabalDescription)+++cabalSpec :: Spec+cabalSpec = describe "Cabal parsing" $ do+ curDir <- runIO getCurrentDirectory++ it "finds .cabal for policeman" $+ runCabal curDir >>= (`shouldSatisfy` isRight)+ it "doesn't find .cabal in src/" $ do+ let srcDir = curDir </> "src"+ runCabal srcDir `shouldReturn` Left (NoCabalFile srcDir)+ it "fails on non-existent directory" $ do+ let abcDir = curDir </> "abc"+ runCabal abcDir `shouldReturn` Left (NoSuchDirectory abcDir)+ where+ runCabal :: FilePath -> IO (Either CabalError GenericPackageDescription)+ runCabal = runExceptT . findCabalDescription
+ test/Test/Policeman/Version.hs view
@@ -0,0 +1,83 @@+{-# LANGUAGE NumericUnderscores #-}++module Test.Policeman.Version+ ( versionSpec+ , versionRoundtripText+ , versionRoundtripInts+ ) where++import Hedgehog (MonadGen, Property, forAll, property, (===))+import Test.Hspec (Spec, describe, it, shouldBe, shouldSatisfy)++import Policeman.Core.Version (Version (..), versionFromIntList, versionFromText, versionToIntList,+ versionToText)++import qualified Data.Text as Text+import qualified Hedgehog.Gen as Gen+import qualified Hedgehog.Range as Range+++-- | Version parsing unit tests.+versionSpec :: Spec+versionSpec = describe "Version parsing" $ do+ describe "From Text" $ do+ it "parses 1.2.3.4" $+ versionFromText "1.2.3.4" `shouldBe` Just (Version 1 2 3 4 "1.2.3.4")+ it "parses 1.2.3" $+ versionFromText "1.2.3" `shouldBe` Just (Version 1 2 3 0 "1.2.3")+ it "parses 1.2" $+ versionFromText "1.2" `shouldBe` Just (Version 1 2 0 0 "1.2")+ it "parses 1" $+ versionFromText "1" `shouldBe` Just (Version 1 0 0 0 "1")+ it "parses 00" $+ versionFromText "00" `shouldBe` Just (Version 0 0 0 0 "00")+ it "does not parse letters" $+ versionFromText "1.2.3.a" `shouldSatisfy` isNothing+ it "does not parse trailing dot" $+ versionFromText "1.2.3." `shouldSatisfy` isNothing+ it "does not parse leading dot" $+ versionFromText ".1.2.3" `shouldSatisfy` isNothing+ describe "From List of Ints" $ do+ it "parses [1,2,3,4]" $+ versionFromIntList [1,2,3,4] `shouldBe` Just (Version 1 2 3 4 "1.2.3.4")+ it "parses [1,2,3]" $+ versionFromIntList [1,2,3] `shouldBe` Just (Version 1 2 3 0 "1.2.3")+ it "parses [1,2]" $+ versionFromIntList [1,2] `shouldBe` Just (Version 1 2 0 0 "1.2")+ it "parses [1]" $+ versionFromIntList [1] `shouldBe` Just (Version 1 0 0 0 "1")+ it "parses [1,2,3,4,5]" $+ versionFromIntList [1,2,3,4,5] `shouldBe` Just (Version 1 2 3 4 "1.2.3.4.5")++-- | Parsing to/from 'Text' works properly.+versionRoundtripText :: Property+versionRoundtripText = property $ do+ preVersion <- forAll genVersion+ let version = preVersion { versionText = versionToText preVersion }+ versionFromText (versionToText version) === Just version++-- | Parsing to/from '[Int]' works properly.+versionRoundtripInts :: Property+versionRoundtripInts = property $ do+ version <- forAll genVersion+ versionFromIntList (versionToIntList version) === Just version++-- | Generates random version.+genVersion :: forall m . (MonadGen m) => m Version+genVersion = do+ versionA <- genInt+ versionB <- genInt+ versionC <- genInt+ versionD <- genInt+ pure Version+ { versionText = Text.intercalate "." $ map show+ [ versionA+ , versionB+ , versionC+ , versionD+ ]+ , ..+ }+ where+ genInt :: m Int+ genInt = Gen.int (Range.constant 0 20_000)