packages feed

haskell-gha (empty) → 1.0

raw patch · 60 files changed

+8397/−0 lines, 60 filesdep +Cabaldep +Cabal-syntaxdep +base

Dependencies added: Cabal, Cabal-syntax, base, bytestring, directory, filepath, haskell-gha, optparse-applicative, parsec, process, tasty, tasty-hunit, temporary, text, time, transformers, yamlet

Files

+ CHANGELOG.md view
@@ -0,0 +1,2 @@+# haskell-gha-1.0 (2026-12-02)+* Initial release.
+ LICENSE view
@@ -0,0 +1,29 @@+Copyright (c) 2026, Andrzej Rybczak++All rights reserved.++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,117 @@+# haskell-gha++[![CI](https://github.com/arybczak/haskell-gha/actions/workflows/haskell-gha.yaml/badge.svg?branch=master)](https://github.com/arybczak/haskell-gha/actions/workflows/haskell-gha.yaml)+[![Hackage](https://img.shields.io/hackage/v/haskell-gha.svg)](https://hackage.haskell.org/package/haskell-gha)++`haskell-gha` writes a GitHub Actions workflow for a Haskell cabal project. The+workflow builds and tests the project on each GHC version from the `tested-with`+field of its packages, in separate jobs. Only Linux is supported.++## Features++- A new GHC release needs no new release of the tool. GHCup installs each+  version, and a series, e.g. `^>= 9.12`, gets its newest release.+- The workflow builds with the project's own `cabal.project`, so CI uses the+  same settings as a local build.+- The jobs build and test the content of the source tarballs that `cabal sdist`+  makes, so CI finds a file that the `.cabal` file does not list before your+  users do.+- You write service containers, hook steps and extra matrix axes in plain GitHub+  Actions YAML, and the tool copies them to the workflow.+- The jobs run on the runner image, or optionally in a job container.+- A job saves a new cache only when its build plan changes.+- Optional jobs test the oldest dependency versions that the bounds allow.+- Optional checks with doctest, fourmolu and HLint.+- `haskell-gha --check` tells whether the committed workflows are up to date.++## Quick start++Install the tool from Hackage:++```+cabal install haskell-gha+```++Give each package of the project its GHC versions in `tested-with`. Each version+is an exact release or a major series, e.g.:++```+tested-with: GHC == 9.6.7 || ^>= 9.10 || ^>= 9.12+```++In the root of your repository, generate the workflow:++```+haskell-gha --generate+```++The tool generates `.github/workflows/haskell-gha.yaml`. Commit this file. After a+change to `tested-with`, to the packages of the project or to the configuration+file of haskell-gha, regenerate the workflow:++```+haskell-gha+```++## Example++The configuration file is `.github/haskell-gha.conf.yaml`, and it needs only the+keys that differ from the defaults. This configuration is for a project that+needs the libsodium library and whose tests use Postgres:++```yaml+branches: [master]+apt: [libsodium-dev]+dependencies: both+services:+  postgres:+    image: postgres:18+    env:+      POSTGRES_PASSWORD: postgres+    ports: ['5432:5432']+    options: >-+      --health-cmd pg_isready+      --health-interval 5s+      --health-retries 10+hooks:+  after-build:+  - name: Create the test database+    run: psql -h localhost -U postgres -c 'CREATE DATABASE test'+    env:+      PGPASSWORD: postgres+doctest: {}+fourmolu:+  version: 0.21.0.0+```++For a package with `tested-with: GHC == 9.6.7 || ^>= 9.10 || ^>= 9.12`, GitHub+shows these jobs:++```+Fourmolu+GHC 9.6.7, newest+GHC 9.6.7, oldest+GHC 9.10, newest+GHC 9.10, oldest+GHC 9.12, newest+GHC 9.12, oldest+```++- The fourmolu job checks the formatting.+- Each GHC version has two build jobs. The `newest` job builds with the newest+  dependency versions that the bounds allow, and the `oldest` job with the+  oldest ones. Each job installs `libsodium-dev` and starts Postgres. After the+  build, it creates the test database, and then it runs the tests and doctest.++The tool generates+[this workflow](https://github.com/arybczak/haskell-gha/blob/master/tests/golden/readme/expected.yaml)+from the configuration.++## Documentation++- [Configuration](https://github.com/arybczak/haskell-gha/blob/master/docs/configuration.md):+  each key of the configuration file.+- [Guide](https://github.com/arybczak/haskell-gha/blob/master/docs/guide.md):+  the command line, the steps of the workflow, the GHC versions, the+  dependencies, the source tarballs, the container, the caches, common failures+  and known limits.
+ app/Main.hs view
@@ -0,0 +1,23 @@+module Main (main) where++import Control.Monad+import Data.Version+import Options.Applicative+import System.Exit+import System.IO++import HaskellGha.Command+import HaskellGha.Command.Options+import Paths_haskell_gha++main :: IO ()+main = do+  -- The messages quote lines of the user's files, and the locale can be ASCII,+  -- e.g. in a container that sets no LANG.+  hSetEncoding stdout utf8+  hSetEncoding stderr utf8+  problems <-+    runCommand "." =<< execParser (optionsParser (showVersion version))+  unless (null problems) $ do+    hPutStr stderr (unlines problems)+    exitFailure
+ haskell-gha.cabal view
@@ -0,0 +1,138 @@+cabal-version:      3.8+build-type:         Simple+name:               haskell-gha+version:            1.0+license:            BSD-3-Clause+license-file:       LICENSE+category:           Development+maintainer:         andrzej@rybczak.net+author:             Andrzej Rybczak+synopsis:           Generate a GitHub Actions workflow for a Haskell cabal project.++description:+  Generate a GitHub Actions workflow that builds and tests a Haskell cabal+  project on each GHC version from @tested-with@.++extra-doc-files:+  CHANGELOG.md+  README.md++-- The fixtures of the golden tests.+extra-source-files:+  tests/golden/**/*.cabal+  tests/golden/**/*.hs+  tests/golden/**/*.project+  tests/golden/**/*.yaml+  tests/golden/**/args++tested-with: GHC ^>= { 9.6, 9.8, 9.10, 9.12, 9.14, 10.0 }++bug-reports:   https://github.com/arybczak/haskell-gha/issues+source-repository head+  type:     git+  location: https://github.com/arybczak/haskell-gha.git++common language+    ghc-options:        -Wall+                        -Wunused-packages+                        -Werror=ambiguous-fields+                        -Werror=missing-deriving-strategies+                        -Werror=prepositive-qualified-module++    default-language:   GHC2021++    default-extensions: DataKinds+                        DeepSubsumption+                        DerivingStrategies+                        DerivingVia+                        DuplicateRecordFields+                        LambdaCase+                        NoFieldSelectors+                        NoStarIsType+                        OverloadedRecordDot+                        OverloadedStrings+                        RecordWildCards+                        RoleAnnotations+                        StrictData+                        TypeFamilies+                        UndecidableInstances++library internal+    import:         language++    visibility:     private++    build-depends:    base                 >= 4.18     && < 5+                    , bytestring           >= 0.11+                    , Cabal                >= 3.14     && < 3.20+                    , Cabal-syntax         >= 3.14     && < 3.20+                    , directory            >= 1.3+                    , filepath             >= 1.4+                    , yamlet               >= 1.0      && < 1.1+                    , optparse-applicative >= 0.17     && < 0.20+                    , parsec               >= 3.1+                    , text                 >= 2.0+                    , transformers         >= 0.5.6++    hs-source-dirs:  src++    exposed-modules: HaskellGha.Check+                     HaskellGha.Command+                     HaskellGha.Command.Header+                     HaskellGha.Command.Options+                     HaskellGha.Config+                     HaskellGha.Path+                     HaskellGha.Project+                     HaskellGha.Project.Compat+                     HaskellGha.Project.Ghc+                     HaskellGha.Workflow+                     HaskellGha.Workflow.Script+                     HaskellGha.Workflow.Validate+                     HaskellGha.Yaml++executable haskell-gha+    import:         language++    build-depends:    base+                    , haskell-gha:internal+                    , optparse-applicative++    hs-source-dirs: app++    main-is:        Main.hs++    autogen-modules: Paths_haskell_gha++    other-modules:   Paths_haskell_gha++test-suite test+    import:         language++    build-depends:    base+                    , bytestring+                    , Cabal-syntax+                    , directory+                    , filepath+                    , haskell-gha:internal+                    , optparse-applicative+                    , process+                    , tasty                >= 1.4      && < 1.6+                    , tasty-hunit          >= 0.10     && < 0.11+                    , temporary            >= 1.3      && < 1.4+                    , text+                    , time                 >= 1.9+                    , yamlet++    hs-source-dirs: tests++    ghc-options:    -threaded -with-rtsopts=-N++    type:           exitcode-stdio-1.0+    main-is:        Main.hs++    other-modules:  HaskellGha.Test.Config+                    HaskellGha.Test.Golden+                    HaskellGha.Test.Helpers+                    HaskellGha.Test.Project+                    HaskellGha.Test.Workflow+                    HaskellGha.Test.Yaml
+ src/HaskellGha/Check.hs view
@@ -0,0 +1,51 @@+-- | Checks that collect all their errors.+module HaskellGha.Check+  ( -- * Check+    Validation+  , Check+  , runCheck+  , failure+  , fromEither+  , fromErrors+  ) where++-- | A computation that collects all errors of its independent parts. In a+-- @do@ block, a bind runs the rest only if its check succeeds, and a+-- statement without a bind collects its errors with the errors of the rest.+newtype Validation e a = Validation (Either [e] a)+  deriving stock (Show)++-- | A check with error messages.+type Check = Validation String++instance Functor (Validation e) where+  fmap f (Validation r) = Validation (fmap f r)++instance Applicative (Validation e) where+  pure = Validation . Right+  Validation (Left e1) <*> Validation (Left e2) = Validation (Left (e1 ++ e2))+  Validation (Left e) <*> _ = Validation (Left e)+  Validation (Right f) <*> Validation r = Validation (fmap f r)++-- '>>=' cannot collect the errors of its second part after the first part+-- fails, but '<*>' and '>>' collect them. Thus the instance breaks the laws+-- @(<*>) = ap@ and @m >> k = m >>= \_ -> k@.+instance Monad (Validation e) where+  Validation r >>= f = either (Validation . Left) f r+  (>>) = (*>)++-- | Get the errors or the result.+runCheck :: Validation e a -> Either [e] a+runCheck (Validation r) = r++-- | A check with one error.+failure :: e -> Validation e a+failure e = Validation (Left [e])++-- | Convert an 'Either' with one error.+fromEither :: Either e a -> Validation e a+fromEither = Validation . either (Left . pure) Right++-- | Convert an 'Either' with a list of errors.+fromErrors :: Either [e] a -> Validation e a+fromErrors = Validation
+ src/HaskellGha/Command.hs view
@@ -0,0 +1,178 @@+-- | The commands of the command line: read the configuration and the project,+-- generate each workflow, and write or check its file.+module HaskellGha.Command+  ( -- * Command+    runCommand++    -- * Steps+  , generate+  , findWorkflows+  ) where++import Control.Monad+import Control.Monad.Trans.Except+import Data.ByteString qualified as BS+import Data.Foldable+import Data.List qualified as L+import Data.Maybe+import Data.Text qualified as T+import Data.Text.Encoding qualified as T+import System.Directory+import System.FilePath+import Yamlet++import HaskellGha.Check+import HaskellGha.Command.Header+import HaskellGha.Command.Options+import HaskellGha.Config+import HaskellGha.Path+import HaskellGha.Project+import HaskellGha.Workflow++-- | Run a command of the command line. The result has the errors, and the+-- workflows that are not up to date for 'Check'.+runCommand+  :: FilePath+  -- ^ The root of the repository.+  -> Command+  -> IO [String]+runCommand root = \case+  Generate opts ->+    doesPathExist (root </> ".git") >>= \case+      True -> run False id opts+      False ->+        pure+          [ "The current directory has no .git, so it is not the root of a repository. GitHub reads only the workflows in "+              ++ workflowDirectory+              ++ " of the root, so run haskell-gha --generate there."+          ]+  Regenerate -> everyWorkflow False+  Check -> everyWorkflow True+  where+    -- The errors of the project do not name the workflow, so each error starts+    -- with the file of its workflow.+    everyWorkflow :: Bool -> IO [String]+    everyWorkflow check =+      findWorkflows root >>= \case+        Left errors -> pure errors+        Right workflows ->+          concat <$> traverse (\opts -> run check ((outputPath opts ++ ": ") ++) opts) workflows++    -- The label changes each error of the generation.+    run :: Bool -> (String -> String) -> Options -> IO [String]+    run check label opts =+      runExceptT (outputInRepository *> ExceptT (generate root opts)) >>= \case+        Left errors -> pure (map label errors)+        Right node -> do+          let rendered = T.encodeUtf8 $ renderWorkflow opts node+              output = root </> outputPath opts+          exists <- doesFileExist output+          current <- if exists then Just <$> BS.readFile output else pure Nothing+          let upToDate = current == Just rendered+          if check+            then+              pure+                [ "The workflow "+                    ++ outputPath opts+                    ++ " is not up to date. To update it, run haskell-gha without --check."+                | not upToDate+                ]+            else case current of+              -- The file can be a workflow that the user wrote, and it may not+              -- be committed. A generated file with a broken header is+              -- replaced, so that the run repairs it.+              Just bytes+                | NoHeader <- readHeader opts.output bytes ->+                    pure+                      [ "The workflow "+                          ++ outputPath opts+                          ++ " was not generated by haskell-gha, so the tool does not replace it. Delete the file first, or give another name with --output."+                      ]+              _ ->+                doesDirectoryExist output >>= \case+                  True ->+                    pure+                      [ "The workflow "+                          ++ outputPath opts+                          ++ " is a directory, so the tool does not replace it. Delete the directory first, or give another name with --output."+                      ]+                  False -> do+                    -- A write of the same content changes the mtime. Then tools+                    -- that trust the Git index, e.g. gitk, list the file as+                    -- changed.+                    unless upToDate $ do+                      createDirectoryIfMissing True (takeDirectory output)+                      BS.writeFile output rendered+                    pure []+      where+        outputInRepository :: ExceptT [String] IO ()+        outputInRepository =+          ExceptT $ linkErrors root [("The workflow " ++ outputPath opts, outputPath opts)]++-- | Read the configuration and the project, and generate the workflow. The+-- phases run in order, and each phase shows all its errors.+generate+  :: FilePath+  -- ^ The root of the repository. The paths of the options are relative to it.+  -> Options+  -> IO (Either [String] Node)+generate root opts = runExceptT $ do+  ExceptT $+    linkErrors+      root+      [ ("The configuration file " ++ configPath opts.config, configPath opts.config)+      , ("The project directory " ++ opts.projectDir, opts.projectDir)+      ]+  (config, source) <- ExceptT $ readConfig root opts.config+  project <- ExceptT $ readProject root opts.projectDir+  node <- except $ workflow opts source config project+  ExceptT $ runnerPaths config source project+  pure node+  where+    -- The paths that only the workflow uses. The checks of the workflow already+    -- rejected each path that leads out by its text.+    runnerPaths :: Config -> ConfigSource -> Project -> IO (Either [String] ())+    runnerPaths config source project = do+      hlint <- forM (foldMap (.paths) config.hlint.value) $ \p -> do+        let path = T.unpack p.value.value+        fmap (\r -> (p.offset, "the path " ++ path ++ " " ++ r ++ "."))+          <$> linkProblem root (opts.projectDir </> path)+      imports <-+        linkErrors+          root+          [ (i.location ++ "the imported file " ++ i.target, opts.projectDir </> i.target)+          | i <- project.imports+          , not (isUrl i.target)+          ]+      pure . runCheck $+        traverse_ failure (sourceErrors source (catMaybes hlint)) *> fromErrors imports++-- | The options of each workflow that the tool generated, from the command in+-- its header.+findWorkflows+  :: FilePath+  -- ^ The root of the repository.+  -> IO (Either [String] [Options])+findWorkflows root = do+  exists <- doesDirectoryExist (root </> workflowDirectory)+  -- A directory or a dangling symbolic link is not a workflow.+  names <-+    if exists+      then+        fmap L.sort+          . filterM (doesFileExist . ((root </> workflowDirectory) </>))+          . filter ((`elem` workflowExtensions) . takeExtension)+          =<< listDirectory (root </> workflowDirectory)+      else pure []+  headers <- forM names $ \name ->+    (name,) . readHeader name <$> BS.readFile (root </> workflowDirectory </> name)+  pure $ case [workflowDirectory </> name ++ ": " ++ e | (name, BrokenHeader e) <- headers] of+    [] -> case [opts | (_, Header opts) <- headers] of+      [] ->+        Left+          [ "No workflow in "+              ++ workflowDirectory+              ++ " was generated by haskell-gha. To generate one, run haskell-gha --generate."+          ]+      workflows -> Right workflows+    errors -> Left errors
+ src/HaskellGha/Command/Header.hs view
@@ -0,0 +1,103 @@+-- | The header of a workflow file. It holds the command that generates the+-- file, so a run without @--generate@ can regenerate the file.+module HaskellGha.Command.Header+  ( -- * Writing+    renderWorkflow++    -- * Reading+  , Header (..)+  , readHeader+  ) where++import Data.Bifunctor+import Data.ByteString qualified as BS+import Data.Text qualified as T+import Data.Text.Encoding qualified as T+import Yamlet.Syntax++import HaskellGha.Command.Options+import HaskellGha.Workflow.Script+import HaskellGha.Yaml++-- | Render the workflow with its header comment.+renderWorkflow :: Options -> Node -> T.Text+renderWorkflow opts =+  renderDocument+    -- The header has no tool version, so that two versions with the same output+    -- agree in --check.+    [ headerMarker+    , "  " <> T.unwords (map (shellQuote . T.pack) $ commandLine opts)+    , ""+    , "To regenerate it, run from the root of the repository:"+    , "  haskell-gha"+    , ""+    , "For more information, see https://github.com/arybczak/haskell-gha"+    ]+    separated+  where+    separated :: [T.Text] -> Bool+    separated = \case+      [] -> True+      ["jobs"] -> True+      ["jobs", _, "steps"] -> True+      _ -> False++-- | The first line of the header. The next line has the command.+headerMarker :: T.Text+headerMarker = "Do not edit this file, it was generated by the following command:"++-- | The header of a workflow file.+data Header+  = -- | The first line is not the marker, so the tool did not generate the+    -- file.+    NoHeader+  | -- | The tool generated the file, but the header is broken.+    BrokenHeader String+  | -- | The options of the command in the header.+    Header Options++-- | Read the header of a workflow file. The output of the command must be the+-- file itself.+readHeader+  :: FilePath+  -- ^ The name of the file in 'workflowDirectory'.+  -> BS.ByteString+  -> Header+readHeader name bytes = case T.lines (T.decodeUtf8Lenient bytes) of+  marker : rest+    | commentText marker == Just headerMarker -> either BrokenHeader Header $ case rest of+        command : _+          | Just text <- commentText command -> do+              args <-+                maybe (Left "the command in the header has a quote without its end") Right $+                  shellWords (T.unpack text)+              opts <- first ("the command in the header is not valid: " ++) (parseCommandLine args)+              if opts.output == name+                then Right opts+                else+                  Left $+                    "the command in the header writes the workflow to "+                      ++ outputPath opts+                      ++ ", not to this file"+        _ -> Left "the header has no command on its second line"+  _ -> NoHeader+  where+    commentText :: T.Text -> Maybe T.Text+    commentText = fmap T.strip . T.stripPrefix "#"++    -- The words of a command line from 'shellQuote'.+    shellWords :: String -> Maybe [String]+    shellWords s = case dropWhile (== ' ') s of+      "" -> Just []+      s' -> do+        (w, rest) <- shellWord s'+        (w :) <$> shellWords rest++    shellWord :: String -> Maybe (String, String)+    shellWord = \case+      '\'' : rest -> case break (== '\'') rest of+        (quoted, _ : rest') -> first (quoted ++) <$> shellWord rest'+        (_, []) -> Nothing+      '\\' : c : rest -> first (c :) <$> shellWord rest+      c : rest | c /= ' ' -> first (c :) <$> shellWord rest+      rest -> Just ("", rest)
+ src/HaskellGha/Command/Options.hs view
@@ -0,0 +1,225 @@+{-# LANGUAGE ApplicativeDo #-}++-- | The command line options.+module HaskellGha.Command.Options+  ( -- * Options+    Command (..)+  , Options (..)+  , defaultOptions+  , outputPath+  , optionsParser+  , commandLine+  , parseCommandLine++    -- * Paths+  , workflowDirectory+  , workflowExtensions+  ) where++import Data.Char+import Data.List qualified as L+import Options.Applicative+import System.FilePath++import HaskellGha.Config+import HaskellGha.Path++-- | What the tool does.+data Command+  = -- | Generate one workflow, with @--generate@.+    Generate Options+  | -- | Regenerate each workflow, with the command in its header.+    Regenerate+  | -- | Make sure that each generated workflow is up to date, with+    -- @--check@.+    Check+  deriving stock (Eq, Show)++-- | The options of one workflow.+data Options = Options+  { config :: ConfigFile+  , projectDir :: FilePath+  , output :: FilePath+  -- ^ The name of the workflow file in 'workflowDirectory'.+  }+  deriving stock (Eq, Show)++-- | The options without arguments.+defaultOptions :: Options+defaultOptions =+  Options+    { config = DefaultConfigFile+    , projectDir = "."+    , output = "haskell-gha.yaml"+    }++-- | The path of the workflow file, relative to the root of the repository.+outputPath :: Options -> FilePath+outputPath opts = workflowDirectory </> opts.output++-- | The directory of the workflow files. GitHub reads only the files directly+-- in it.+workflowDirectory :: FilePath+workflowDirectory = ".github/workflows"++-- | The extensions of the files that GitHub reads as workflows.+workflowExtensions :: [String]+workflowExtensions = [".yml", ".yaml"]++-- | The parser of the command line.+optionsParser+  :: String+  -- ^ The version of the tool.+  -> ParserInfo Command+optionsParser version =+  info+    ((generate <|> check) <**> versionOption <**> helper)+    ( fullDesc+        <> progDesc+          ( "Write a GitHub Actions workflow that builds and tests a cabal project on each GHC version from tested-with. Without --generate, regenerate each workflow in "+              ++ workflowDirectory+              ++ ", with the command in its header."+          )+    )+  where+    generate :: Parser Command+    generate =+      flag' () (long "generate" <> help "Generate one workflow with the options below")+        *> (Generate <$> options)++    check :: Parser Command+    check =+      flag+        Regenerate+        Check+        ( long "check"+            <> help "Do not write the workflow files. Exit with code 1 if one is not up to date."+        )++    versionOption :: Parser (a -> a)+    versionOption =+      infoOption+        ("haskell-gha " ++ version)+        (long "version" <> short 'v' <> help "Show the version")++-- | The parser of the options of one workflow.+options :: Parser Options+options = do+  config <-+    option+      configReader+      ( long "config"+          <> metavar "FILE"+          <> value DefaultConfigFile+          <> showDefaultWith (const defaultConfigPath)+          <> help "The configuration file"+      )+  projectDir <-+    option+      projectDirReader+      ( long "project-dir"+          <> metavar "DIR"+          <> value defaultOptions.projectDir+          <> showDefault+          <> help "The directory that contains cabal.project or the package"+      )+  output <-+    option+      outputReader+      ( long "output"+          <> metavar "NAME"+          <> value defaultOptions.output+          <> showDefault+          <> help ("The name of the workflow file in " ++ workflowDirectory)+      )+  pure Options {..}+  where+    -- A run without --generate reads the file from the header, also in another+    -- checkout of the repository, e.g. with --check in CI.+    configReader :: ReadM ConfigFile+    configReader = ConfigFile <$> (pathReader >>= inRepository "The configuration file")++    -- The workflow uses the directory on the runner, so it must be in the+    -- repository.+    projectDirReader :: ReadM FilePath+    projectDirReader = pathReader >>= inRepository "The project directory"++    inRepository :: String -> FilePath -> ReadM FilePath+    inRepository what path+      | leadsOut path =+          readerError $+            what+              ++ " "+              ++ show path+              ++ " is not in the repository. Give a path relative to the root of the repository."+      | otherwise = pure path++    -- GitHub reads only these files, and a run without --generate finds only+    -- them.+    outputReader :: ReadM FilePath+    outputReader =+      pathReader >>= \case+        name+          | any isPathSeparator name ->+              readerError $+                "The workflow file name "+                  ++ show name+                  ++ " contains a directory. GitHub reads only the files directly in "+                  ++ workflowDirectory+                  ++ ", so give only the name of the file, e.g. ci.yaml."+          | ',' `elem` name ->+              readerError $+                "The workflow file name "+                  ++ show name+                  ++ " contains a comma. The name is a part of the cache keys, and actions/cache does not accept a comma in a key."+          | takeExtension name `notElem` workflowExtensions ->+              readerError $+                "The workflow file name "+                  ++ show name+                  ++ " does not end with "+                  ++ L.intercalate " or " workflowExtensions+                  ++ ". GitHub reads only such files."+          | otherwise -> pure name++    -- The header of the workflow has the command line on one comment line, and+    -- a line break ends the comment. YAML does not allow most other control+    -- characters. YAML 1.1, which GitHub reads, also breaks a line at U+2028+    -- and U+2029, so the renderer splits the comment there.+    pathReader :: ReadM FilePath+    pathReader =+      str >>= \path -> case () of+        _+          | null path -> readerError "The path is empty."+          | any isControl path ->+              readerError $+                "The path "+                  ++ show path+                  ++ " contains a control character, e.g. a tab or a line break."+          | any (`elem` ['\x2028', '\x2029']) path ->+              readerError $+                "The path "+                  ++ show path+                  ++ " contains U+2028 or U+2029, which YAML reads as a line break."+          | otherwise -> pure path++-- | The command line that gives the options. It contains @--config@ if the user+-- gave it, and each other option that is not a default.+commandLine :: Options -> [String]+commandLine opts =+  "haskell-gha"+    : "--generate"+    : concat+      ( [["--project-dir", opts.projectDir] | opts.projectDir /= defaultOptions.projectDir]+          ++ [["--config", path] | ConfigFile path <- [opts.config]]+          ++ [["--output", opts.output] | opts.output /= defaultOptions.output]+      )++-- | The options of a command line from 'commandLine'.+parseCommandLine :: [String] -> Either String Options+parseCommandLine = \case+  "haskell-gha" : "--generate" : args ->+    case execParserPure defaultPrefs (info options mempty) args of+      Success opts -> Right opts+      Failure failure -> Left . fst $ renderFailure failure "haskell-gha --generate"+      CompletionInvoked _ -> Left "the command asks for a shell completion"+  _ -> Left "the command does not start with haskell-gha --generate"
+ src/HaskellGha/Config.hs view
@@ -0,0 +1,710 @@+{-# OPTIONS_GHC -Wno-orphans #-}++-- | The configuration file.+module HaskellGha.Config+  ( -- * Configuration+    Config (..)+  , CabalVersion (..)+  , Container (..)+  , Submodules (..)+  , Dependencies (..)+  , BuildFrom (..)+  , Hooks (..)+  , Doctest (..)+  , Fourmolu (..)+  , HLint (..)+  , FailOn (..)+  , Actions (..)+  , ActionRef (..)+  , defaultConfig++    -- * Values+  , Optional (..)+  , Positive (..)+  , MappingNode (..)+  , Permissions (..)+  , RunsOn (..)+  , Matrix (..)+  , GhcOptions (..)+  , ProjectText (..)+  , Pattern (..)+  , HLintPath (..)++    -- * Matrix+  , combinationValues++    -- * Reading+  , ConfigFile (..)+  , ConfigSource (..)+  , emptySource+  , sourceErrors+  , defaultConfigPath+  , configPath+  , readConfig+  , parseConfig+  ) where++import Control.Monad+import Data.Bifunctor+import Data.ByteString qualified as BS+import Data.Char+import Data.Foldable+import Data.Functor+import Data.List.NonEmpty qualified as NE+import Data.Maybe+import Data.Text qualified as T+import Distribution.Parsec+import Distribution.Version+import System.Directory hiding (Permissions)+import System.FilePath+import Yamlet+import Yamlet.Syntax++import HaskellGha.Yaml++-- | The configuration.+data Config = Config+  { name :: Commented T.Text+  , cabalVersion :: CabalVersion+  , runsOn :: Commented RunsOn+  , container :: Optional Container+  , timeoutMinutes :: Positive+  , branches :: Commented (NE.NonEmpty (Commented T.Text))+  , submodules :: Submodules+  , matrix :: Commented Matrix+  , apt :: [T.Text]+  , services :: Optional (Commented MappingNode)+  , permissions :: Commented Permissions+  , hooks :: Hooks+  , ghcOptions :: GhcOptions+  , cabalProjectLocal :: ProjectText+  , cabalJobs :: Positive+  , tests :: Bool+  , benchmarks :: Bool+  , dependencies :: Dependencies+  , doctest :: Optional Doctest+  , cabalCheck :: Bool+  , buildFrom :: BuildFrom+  , haddock :: Bool+  , fourmolu :: Optional Fourmolu+  , hlint :: Optional HLint+  , actions :: Actions+  }+  deriving stock (Eq, Show, Generic)+  deriving (FromYaml) via GenericYaml Config++instance GenericYamlOptions Config where+  yamlOptions = options+  yamlDefault = Just defaultConfig++-- | The configuration of the HLint job.+data HLint = HLint+  { version :: ~Version+  , failOn :: FailOn+  , paths :: [Located HLintPath]+  -- ^ Relative to the project directory. An empty list gives the project+  -- directory.+  , runsOn :: Optional (Commented RunsOn)+  -- ^ 'Nothing' gives the @runs-on@ of the build jobs.+  }+  deriving stock (Eq, Show, Generic)+  deriving (FromYaml) via GenericYaml HLint++instance GenericYamlOptions HLint where+  yamlOptions = options+  yamlDefault = Just defaultHLint++-- | The lowest hint severity that fails the HLint job.+data FailOn+  = FailNever+  | FailError+  | FailWarning+  | FailSuggestion+  deriving stock (Eq, Show, Generic)+  deriving (FromYaml, ToYaml) via GenericYaml FailOn++instance GenericYamlOptions FailOn where+  yamlOptions = defaultYamlOptions {constructorTagModifier = map toLower . drop (length @[] "Fail")}++-- | The configuration of the fourmolu job.+data Fourmolu = Fourmolu+  { version :: ~Version+  , patterns :: [Pattern]+  -- ^ The files to check. An empty list gives the default of the action.+  , runsOn :: Optional (Commented RunsOn)+  -- ^ 'Nothing' gives the @runs-on@ of the build jobs.+  }+  deriving stock (Eq, Show, Generic)+  deriving (FromYaml) via GenericYaml Fourmolu++instance GenericYamlOptions Fourmolu where+  yamlOptions = options+  yamlDefault = Just defaultFourmolu++-- | The versions of the actions.+data Actions = Actions+  { checkout :: ActionRef+  , cache :: ActionRef+  -- ^ For both @actions/cache/restore@ and @actions/cache/save@.+  , runFourmolu :: ActionRef+  , hlintSetup :: ActionRef+  , hlintRun :: ActionRef+  }+  deriving stock (Eq, Show, Generic)+  deriving (FromYaml) via GenericYaml Actions++instance GenericYamlOptions Actions where+  yamlOptions = options+  yamlDefault = Just defaultConfig.actions++-- | The version of an action in @uses@.+data ActionRef = ActionRef+  { repository :: Maybe T.Text+  -- ^ A repository in place of the default one, e.g. a fork.+  , ref :: T.Text+  -- ^ The Git ref after the @\@@.+  }+  deriving stock (Eq, Show)++-- | A Git ref, e.g. @v7@, or a repository with a Git ref, e.g.+-- @runs-on/cache\@v4@.+instance FromYaml ActionRef where+  parseYaml = withText $ \t -> case T.splitOn "@" t of+    [r] | word r -> pure ActionRef {repository = Nothing, ref = r}+    [repo, r]+      | [owner, name] <- T.splitOn "/" repo+      , all word [owner, name, r] ->+          pure ActionRef {repository = Just repo, ref = r}+    _ ->+      fail "expected a Git ref, e.g. v7, or a repository with a Git ref, e.g. runs-on/cache@v4"+    where+      word :: T.Text -> Bool+      word w = not (T.null w) && not (T.any isSpace w)++-- | The cabal release for GHCup. A cabal release has four parts.+newtype CabalVersion = CabalVersion Version+  deriving stock (Eq, Show)++instance FromYaml CabalVersion where+  parseYaml = withText $ \t -> case simpleParsec (T.unpack t) of+    Just v+      | length (versionNumbers v) /= 4 ->+          fail expected+      | take 2 (versionNumbers v) < [3, 12] ->+          fail "the tool supports only cabal 3.12 and later"+      | otherwise -> pure $ CabalVersion v+    Nothing -> fail expected+    where+      expected :: String+      expected = "expected a release with four parts, e.g. 3.16.1.0"++-- | The image of the job container of the build jobs, e.g.+-- @buildpack-deps:26.04@.+newtype Container = Container {image :: T.Text}+  deriving stock (Eq, Show)++instance FromYaml Container where+  parseYaml = oneOf [(i, Container i) | v <- versions, let i = "buildpack-deps:" <> v]+    where+      -- The Ubuntu versions of the buildpack-deps images of the LTS releases,+      -- from the file library/buildpack-deps of docker-library/official-images+      -- on 2026-09-27. An interim release has support for only 9 months, so the+      -- list leaves it out. The tool accepts only the images that it knows,+      -- because another image can lack a package that the workflow needs, e.g.+      -- git or xz-utils.+      versions :: [T.Text]+      versions = ["22.04", "24.04", "26.04"]++-- | The versions of the dependencies that the build jobs use.+data Dependencies+  = DependenciesNewest+  | -- | The oldest versions that the bounds allow.+    DependenciesOldest+  | -- | A job for each of the two, as the values of a matrix axis.+    DependenciesBoth+  deriving stock (Eq, Show, Generic)+  deriving (FromYaml) via GenericYaml Dependencies++instance GenericYamlOptions Dependencies where+  yamlOptions =+    defaultYamlOptions+      { constructorTagModifier = map toLower . drop (length @[] "Dependencies")+      }++-- | The code that the build jobs build and test.+data BuildFrom+  = -- | The content of the source tarballs.+    BuildFromTarballs+  | BuildFromCheckout+  deriving stock (Eq, Show, Generic)+  deriving (FromYaml) via GenericYaml BuildFrom++instance GenericYamlOptions BuildFrom where+  yamlOptions =+    defaultYamlOptions+      { constructorTagModifier = map toLower . drop (length @[] "BuildFrom")+      }++-- | The Git submodules that the build jobs fetch.+data Submodules+  = NoSubmodules+  | -- | The submodules of the repository, without their own submodules.+    TopSubmodules+  | RecursiveSubmodules+  deriving stock (Eq, Show)++instance FromYaml Submodules where+  parseYaml n = case view n of+    StringView "recursive" -> pure RecursiveSubmodules+    BoolView True -> pure TopSubmodules+    BoolView False -> pure NoSubmodules+    _ -> failAt n "expected true, false or recursive"++-- | The steps that the tool puts in the workflow.+data Hooks = Hooks+  { afterSetup :: [MappingNode]+  , afterBuild :: [MappingNode]+  }+  deriving stock (Eq, Show, Generic)+  deriving (FromYaml) via GenericYaml Hooks++instance GenericYamlOptions Hooks where+  yamlOptions = options+  yamlDefault = Just defaultConfig.hooks++-- | The configuration of doctest.+data Doctest = Doctest+  { ghc :: Located VersionRange+  , version :: Optional VersionRange+  , skipPackages :: [Located T.Text]+  , options :: [T.Text]+  }+  deriving stock (Eq, Show, Generic)+  deriving (FromYaml) via GenericYaml Doctest++instance GenericYamlOptions Doctest where+  yamlOptions = options+  yamlDefault = Just defaultDoctest++-- | The options of the records of the configuration.+options :: YamlOptions+options = defaultYamlOptions {fieldLabelModifier = kebabCase}++-- | The configuration if the file does not exist.+defaultConfig :: Config+defaultConfig =+  Config+    { name = bare "CI"+    , cabalVersion = CabalVersion (mkVersion [3, 16, 1, 0])+    , runsOn = bare (RunsOn (plain "ubuntu-26.04"))+    , container = Optional Nothing+    , -- Without a limit, GitHub stops a job only after six hours. A build+      -- usually takes way less than an hour, so 60 leaves room for a build+      -- without a cache.+      timeoutMinutes = Positive 60+    , branches = bare (bare "master" NE.:| [bare "main"])+    , submodules = NoSubmodules+    , matrix =+        bare+          Matrix+            { leading = []+            , entries = []+            , axes = []+            , include = []+            , exclude = []+            }+    , apt = []+    , services = Optional Nothing+    , permissions = bare (Permissions (mapping ["contents" .= plain "read"]))+    , hooks = Hooks {afterSetup = [], afterBuild = []}+    , ghcOptions = GhcOptions "-Werror"+    , cabalProjectLocal = ProjectText ""+    , -- The standard Linux runners of GitHub have 4 CPUs.+      cabalJobs = Positive 4+    , tests = True+    , benchmarks = True+    , dependencies = DependenciesNewest+    , doctest = Optional Nothing+    , cabalCheck = True+    , buildFrom = BuildFromTarballs+    , haddock = True+    , fourmolu = Optional Nothing+    , hlint = Optional Nothing+    , actions =+        Actions+          { checkout = ActionRef {repository = Nothing, ref = "v7"}+          , cache = ActionRef {repository = Nothing, ref = "v6"}+          , runFourmolu = ActionRef {repository = Nothing, ref = "v13"}+          , -- The commits "Upgrade to node24". Each release still needs+            -- Node.js 20.+            hlintSetup =+              ActionRef+                { repository = Nothing+                , ref = "c04631035af0a6787c85e33b3ea0128b8568b590"+                }+          , hlintRun =+              ActionRef+                { repository = Nothing+                , ref = "d009541bdae0b8492992416e665bb6df8a3b5cde"+                }+          }+    }+  where+    bare :: a -> Commented a+    bare a = Commented a noComments++-- | The values of the keys that an @hlint@ field leaves out.+defaultHLint :: HLint+defaultHLint =+  HLint+    { version = requiredField+    , failOn = FailSuggestion+    , paths = []+    , runsOn = Optional Nothing+    }++-- | The values of the keys that a @fourmolu@ field leaves out.+defaultFourmolu :: Fourmolu+defaultFourmolu =+  Fourmolu+    { version = requiredField+    , patterns = []+    , runsOn = Optional Nothing+    }++-- | The values of the keys that a @doctest@ field leaves out.+defaultDoctest :: Doctest+defaultDoctest =+  Doctest+    { ghc = Located anyVersion noOffset+    , version = Optional Nothing+    , skipPackages = []+    , options = []+    }++----------------------------------------+-- Values++-- | A version, e.g. @0.21.0.0@. It must be a string, because YAML reads e.g.+-- @3.10@ as the number 3.1.+instance FromYaml Version where+  parseYaml = withText $ \t -> maybe (fail "expected a version, e.g. 0.21.0.0") pure (simpleParsec (T.unpack t))++-- | A version range, e.g. @>=9.6 && <9.14@.+instance FromYaml VersionRange where+  parseYaml = withText $ \t ->+    maybe+      (fail "expected a version range, e.g. '>=1.2' or '==1.2.3'")+      pure+      (simpleParsec (T.unpack t))++-- | A value that only a missing key leaves out. Unlike for 'Maybe', null is an+-- error.+newtype Optional a = Optional {value :: Maybe a}+  deriving newtype (Eq, Show)++instance FromYaml a => FromYaml (Optional a) where+  parseYaml n = Optional . Just <$> parseYaml n+  parseYamlField k n = Optional . Just <$> parseYamlField k n++-- | A positive integer.+newtype Positive = Positive {value :: Int}+  deriving newtype (Eq, Show)++instance FromYaml Positive where+  parseYaml n = case view n of+    IntView i+      | i > 0+      , i <= toInteger (maxBound @Int) ->+          pure $ Positive (fromInteger i)+    _ -> failAt n "expected a positive integer"++-- | A mapping that the workflow copies, e.g. a step of a hook.+newtype MappingNode = MappingNode {value :: Node}+  deriving newtype (Eq, Show, ToYaml)++instance FromYaml MappingNode where+  parseYaml n = case n.content of+    MappingContent {} -> MappingNode <$> parseYaml n+    _ -> typeMismatch "a mapping" n++-- | The permissions of the workflow: a mapping, @read-all@ or @write-all@.+newtype Permissions = Permissions {value :: Node}+  deriving newtype (Eq, Show, ToYaml)++instance FromYaml Permissions where+  parseYaml n = case view n of+    MappingView _ -> Permissions <$> parseYaml n+    StringView t | t `elem` ["read-all", "write-all"] -> Permissions <$> parseYaml n+    _ -> failAt n "expected a mapping, read-all or write-all"++-- | The runner of a job: a label, a list of labels or a mapping, e.g. with+-- @group@ and @labels@.+newtype RunsOn = RunsOn {value :: Node}+  deriving newtype (Eq, Show, ToYaml)++instance FromYaml RunsOn where+  parseYaml n = case view n of+    StringView _ -> RunsOn <$> parseYaml n+    SequenceView _ -> parseYaml @[T.Text] n *> (RunsOn <$> parseYaml n)+    MappingView _ -> RunsOn <$> parseYaml n+    _ -> failAt n "expected a runner label, a list of labels or a mapping"++-- | The @ghc-options@ of the local packages. The workflow writes them as one+-- field of a package stanza, so they must be one line.+newtype GhcOptions = GhcOptions {value :: T.Text}+  deriving newtype (Eq, Show)++instance FromYaml GhcOptions where+  parseYaml = withText $ \t ->+    if T.any (`elem` ['\n', '\r']) (T.dropWhileEnd isSpace t)+      then fail "the value must be one line"+      else pure $ GhcOptions (T.strip t)++-- | Extra text for @cabal.project.local@. The workflow writes the text with a+-- heredoc that ends at the line EOF.+newtype ProjectText = ProjectText {value :: T.Text}+  deriving newtype (Eq, Show)++instance FromYaml ProjectText where+  parseYaml = withText $ \t ->+    if "EOF" `elem` T.lines t+      then fail "a line must not be EOF"+      else pure $ ProjectText t++-- | A pattern of the files that fourmolu checks. The workflow gives the+-- patterns to the action as a literal block with one pattern on each line. The+-- YAML writer breaks the block if its first line starts with a space.+newtype Pattern = Pattern {value :: T.Text}+  deriving newtype (Eq, Show)++instance FromYaml Pattern where+  parseYaml = withText $ \p ->+    if not (T.null p) && T.strip p == p && not (T.any (`elem` ['\n', '\r']) p)+      then pure $ Pattern p+      else fail "a pattern must be one line without spaces at the start or the end"++-- | A path that the HLint job checks. The workflow gives the paths to the+-- action in a JSON array, and a JSON string cannot contain a raw control+-- character.+newtype HLintPath = HLintPath {value :: T.Text}+  deriving newtype (Eq, Show)++instance FromYaml HLintPath where+  parseYaml = withText $ \p -> case () of+    _+      | T.null p -> fail "a path must not be empty"+      | T.any isControl p ->+          fail "a path must not contain a control character, e.g. a tab or a line break"+      | otherwise -> pure $ HLintPath p++----------------------------------------+-- Matrix++-- | The extra axes of the matrix, with @include@ and @exclude@.+data Matrix = Matrix+  { leading :: [Line]+  -- ^ The comments below @matrix:@ and above an empty line before its first+  -- entry. The parser gives the comments below the empty line to that entry.+  , entries :: [(Node, Node)]+  , axes :: [Located T.Text]+  -- ^ The names of the extra axes.+  , include :: [[(T.Text, Located T.Text)]]+  -- ^ The keys of each entry with their string values.+  , exclude :: [[(T.Text, Located T.Text)]]+  -- ^ The keys of each entry with their string values.+  }+  deriving stock (Eq, Show)++-- | The values of a key in the entries of @include@ or @exclude@, e.g. of+-- @ghc@.+combinationValues :: T.Text -> [[(T.Text, Located T.Text)]] -> [Located T.Text]+combinationValues key cs = [v | c <- cs, Just v <- [lookup key c]]++instance FromYaml Matrix where+  parseYaml n = case m.content of+    MappingContent _ es ->+      traverse_ (entry (map (.value) (axes es))) es+        $> Matrix+          { leading = m.comments.before+          , entries = es+          , axes = axes es+          , include = combinations "include" es+          , exclude = combinations "exclude" es+          }+    _ -> typeMismatch "a mapping" n+    where+      -- A copy of every text, so the configuration does not keep the input file+      -- in memory.+      m :: Node+      m = copyNode n++      axes :: [(Node, Node)] -> [Located T.Text]+      axes es =+        [ Located k key.offset+        | (key@Node {content = ScalarContent _ k}, _) <- es+        , k `notElem` ["ghc", "include", "exclude"]+        ]++      combinations :: T.Text -> [(Node, Node)] -> [[(T.Text, Located T.Text)]]+      combinations list es =+        [ [ (f, Located t v.offset)+          | (Node {content = ScalarContent _ f}, v@Node {content = ScalarContent _ t}) <- fields+          ]+        | (Node {content = ScalarContent _ k}, Node {content = SequenceContent _ items}) <- es+        , k == list+        , Node {content = MappingContent _ fields} <- items+        ]++      entry :: [T.Text] -> (Node, Node) -> Parser ()+      entry as = \case+        (key@Node {content = ScalarContent _ k}, v)+          | k == "ghc" ->+              failAt key "the tool makes the ghc axis, so the matrix must not contain it"+          | k `elem` ["include", "exclude"] -> case v.content of+              SequenceContent _ items -> traverse_ (combination as (k == "exclude")) items+              _ -> typeMismatch "a list of mappings" v+          | not (identifier k) ->+              failAt key $+                "the axis name "+                  ++ show (T.unpack k)+                  ++ " is not valid in a GitHub expression. A name must start with a letter or _, and contain only letters, digits, _ and -, e.g. os-version"+          | otherwise -> pure ()+        (key, _) -> failAt key "an axis name must be a string"++      -- The job name refers to each axis as matrix.<name>.+      identifier :: T.Text -> Bool+      identifier t = case T.uncons t of+        Just (c, rest) ->+          (isAsciiAlpha c || c == '_')+            && T.all (\x -> isAsciiAlpha x || isDigit x || x `elem` ['_', '-']) rest+        Nothing -> False+        where+          isAsciiAlpha :: Char -> Bool+          isAsciiAlpha x = isAsciiLower x || isAsciiUpper x++      combination :: [T.Text] -> Bool -> Node -> Parser ()+      combination as isExclude item = case item.content of+        MappingContent _ fields ->+          ghcValue fields+            -- Whether dependencies is a valid key depends on the dependencies+            -- setting, so the checks of the workflow decide it.+            *> when+              isExclude+              ( traverse_+                  (unknownAxis as)+                  [ (key, k)+                  | (key@Node {content = ScalarContent _ k}, _) <- fields+                  , k `notElem` ["ghc", "dependencies"]+                  ]+              )+        _ -> typeMismatch "a mapping" item++      ghcValue :: [(Node, Node)] -> Parser ()+      ghcValue fields = case [v | (Node {content = ScalarContent _ "ghc"}, v) <- fields] of+        Node {content = ScalarContent s _} : _ | s `elem` [SingleQuoted, DoubleQuoted] -> pure ()+        v : _ -> failAt v "a ghc value must be a quoted string, e.g. '9.10'"+        [] -> pure ()++      unknownAxis :: [T.Text] -> (Node, T.Text) -> Parser ()+      unknownAxis as (key, axis)+        | axis `elem` as = pure ()+        | otherwise =+            failAt key $+              T.unpack axis+                ++ " is not an axis of the matrix. The axes are: "+                ++ T.unpack (T.intercalate ", " ("ghc" : as))++----------------------------------------+-- Reading++-- | The location of the configuration file.+data ConfigFile+  = -- | The default file. It can be missing.+    DefaultConfigFile+  | -- | A file that the user names. It must exist, because a typo in its name+    -- would silently give the defaults.+    ConfigFile FilePath+  deriving stock (Eq, Show)++-- | The path of the default configuration file.+defaultConfigPath :: FilePath+defaultConfigPath = ".github/haskell-gha.conf.yaml"++-- | The configuration file, for the errors of the checks after the decode.+data ConfigSource = ConfigSource+  { file :: FilePath+  , input :: T.Text+  , document :: Document+  }++-- | The source of a configuration without a file, e.g. of 'defaultConfig'.+emptySource :: FilePath -> ConfigSource+emptySource file =+  ConfigSource+    { file = file+    , input = ""+    , document = document nullValue+    }++-- | The errors at the offsets of values of the configuration, e.g. of 'Located'+-- values.+sourceErrors :: ConfigSource -> [(Offset, String)] -> [String]+sourceErrors source = map (prettyError source.file) . documentErrors source.input source.document++-- | Read the configuration file. If the default file does not exist, the result+-- is 'defaultConfig'.+readConfig+  :: FilePath+  -- ^ The root of the repository.+  -> ConfigFile+  -> IO (Either [String] (Config, ConfigSource))+readConfig root configFile =+  doesFileExist (root </> file) >>= \case+    True -> parseConfig file <$> BS.readFile (root </> file)+    False ->+      -- The entry of the name in its directory does not show a path such as+      -- . or a/, so the directory needs its own check.+      ((||) <$> doesDirectoryExist (root </> file) <*> hasEntry) <&> \case+        -- Also for the default file, because the defaults would hide the broken+        -- file.+        True ->+          Left+            ["The configuration file " ++ file ++ " is a directory or a broken symbolic link."]+        False -> case configFile of+          DefaultConfigFile -> Right (defaultConfig, emptySource file)+          ConfigFile _ -> Left ["The configuration file " ++ file ++ " does not exist."]+  where+    -- Whether the directory of the file has an entry with its name. Unlike+    -- doesPathExist, this is also true for a broken symbolic link.+    hasEntry :: IO Bool+    hasEntry =+      doesDirectoryExist parent >>= \case+        True -> elem (takeFileName file) <$> listDirectory parent+        False -> pure False+      where+        parent :: FilePath+        parent = takeDirectory (root </> file)++    file :: FilePath+    file = configPath configFile++-- | The path of the configuration file, relative to the root of the repository.+configPath :: ConfigFile -> FilePath+configPath = \case+  DefaultConfigFile -> defaultConfigPath+  ConfigFile path -> path++-- | Parse the configuration. An empty file gives 'defaultConfig'.+parseConfig+  :: FilePath+  -- ^ The file name for the error messages.+  -> BS.ByteString+  -> Either [String] (Config, ConfigSource)+parseConfig file bytes = first (map (prettyError file)) $ do+  input <- first pure (decodeInput bytes)+  (config, doc) <- first NE.toList (decodeWithDocument input)+  pure+    ( fromMaybe defaultConfig config+    , ConfigSource {file = file, input = input, document = doc}+    )
+ src/HaskellGha/Path.hs view
@@ -0,0 +1,108 @@+-- | The rules for the paths that the tool reads or writes, and for the paths+-- that the workflow uses on the runner. The runner has only the repository, at+-- another place than the local checkout.+module HaskellGha.Path+  ( -- * Rules+    leadsOut+  , linkProblem+  , linkErrors++    -- * Text+  , leadsAbove+  , isUrl+  , normalisePath+  ) where++import Control.Exception+import Data.Foldable+import Data.List qualified as L+import System.Directory+import System.FilePath++import HaskellGha.Check++-- | Whether a path, relative to the root of the repository, leads out of it by+-- its text: it is absolute, or its @..@ components lead above the root.+leadsOut :: FilePath -> Bool+leadsOut path = isAbsolute path || leadsAbove path++-- | Whether the @..@ components of a relative path lead above its start, e.g.+-- @a/../../b@.+leadsAbove :: FilePath -> Bool+leadsAbove = any (< 0) . scanl (+) 0 . map depth . splitDirectories+  where+    depth :: FilePath -> Int+    depth = \case+      ".." -> -1+      "." -> 0+      _ -> 1++-- | Whether a location in @cabal.project@, e.g. of an @import:@ line, is a URL+-- and not a path.+isUrl :: String -> Bool+isUrl = L.isInfixOf "://"++-- | One spelling of a path, e.g. @src@ for @./src/@. 'normalise' alone keeps a+-- trailing separator, so @./@ stays @./@ and not @.@.+normalisePath :: FilePath -> FilePath+normalisePath = dropTrailingPathSeparator . normalise++-- | Why a path, relative to the root of the repository, does not work on the+-- runner, if it does not. The path follows each symbolic link, also a broken+-- one, and a @..@ after a link leaves the target of the link, as in the system.+-- A component that does not exist is not a link, so the path can name a file+-- that the tool or the workflow makes.+linkProblem+  :: FilePath+  -- ^ The root of the repository.+  -> FilePath+  -> IO (Maybe String)+linkProblem root path+  | isAbsolute path = pure (Just "leads out of the repository")+  | otherwise = go 0 [] (splitDirectories path)+  where+    -- The arguments are the number of links so far, and the components of the+    -- directory so far, in reverse order.+    go :: Int -> [FilePath] -> [FilePath] -> IO (Maybe String)+    go links dir = \case+      [] -> pure Nothing+      "." : rest -> go links dir rest+      ".." : rest -> case dir of+        _ : up -> go links up rest+        []+          | links == 0 -> pure (Just "leads out of the repository")+          | otherwise -> pure (Just "leads out of the repository through a symbolic link")+      c : rest -> do+        let here = joinPath (reverse (c : dir))+        try @IOException (getSymbolicLinkTarget (root </> here)) >>= \case+          -- Also a path that does not exist.+          Left _ -> go links (c : dir) rest+          Right target+            | links == maxLinks ->+                pure . Just $+                  "goes through more than "+                    ++ show maxLinks+                    ++ " symbolic links, and Linux on the runner follows no more"+            | isAbsolute target ->+                pure . Just $+                  "goes through the symbolic link "+                    ++ here+                    ++ " with an absolute target, but the repository is at another place on the runner. Give the link a relative target"+            | otherwise -> go (links + 1) dir (splitDirectories target ++ rest)++    -- MAXSYMLINKS in include/linux/namei.h, the limit of the links in one path+    -- on the runner.+    maxLinks :: Int+    maxLinks = 40++-- | An error for each path that 'linkProblem' rejects. The paths are relative+-- to the root of the repository, and each comes with the start of its message,+-- e.g. @The project directory a@.+linkErrors+  :: FilePath+  -- ^ The root of the repository.+  -> [(String, FilePath)]+  -> IO (Either [String] ())+linkErrors root =+  fmap (runCheck . traverse_ (traverse_ failure))+    . mapM (\(start, path) -> fmap (\r -> start ++ " " ++ r ++ ".") <$> linkProblem root path)
+ src/HaskellGha/Project.hs view
@@ -0,0 +1,685 @@+{-# LANGUAGE ApplicativeDo #-}++-- | The reader of the project: the local packages and the GHC versions that+-- each package is in the project for.+module HaskellGha.Project+  ( -- * Project+    Project (..)+  , Package (..)+  , MatrixEntry (..)+  , Import (..)++    -- * Reading+  , readProject+  ) where++import Control.Monad+import Control.Monad.Trans.Class+import Control.Monad.Trans.Except+import Data.Bifunctor+import Data.ByteString qualified as BS+import Data.ByteString.Char8 qualified as BS8+import Data.Char+import Data.Foldable+import Data.Functor+import Data.List qualified as L+import Data.Maybe+import Data.Text qualified as T+import Data.Text.Encoding qualified as T+import Distribution.Compiler+import Distribution.Fields+import Distribution.ModuleName qualified as ModuleName+import Distribution.PackageDescription+import Distribution.PackageDescription.Configuration hiding (parseCondition)+import Distribution.PackageDescription.Parsec+import Distribution.Parsec+import Distribution.Pretty+import Distribution.Simple.FileMonitor.Types+import Distribution.Simple.Glob.Internal+import Distribution.System+import Distribution.Utils.Path qualified as Path+import Distribution.Version+import System.Directory+import System.FilePath+import Text.Parsec.Error+import Text.Parsec.Pos++import HaskellGha.Check+import HaskellGha.Path+import HaskellGha.Project.Compat+import HaskellGha.Project.Ghc++-- | A local package.+data Package = Package+  { name :: String+  , directory :: FilePath+  -- ^ Relative to the project directory.+  , ghcRange :: VersionRange+  -- ^ The union of the GHC entries of @tested-with@.+  , hasTestSuite :: Bool+  , doctestArgs :: [[String]]+  -- ^ The doctest arguments for the library and each sublibrary.+  }+  deriving stock (Eq, Show)++-- | An entry of the @ghc@ axis with the packages that are in the project for+-- it.+data MatrixEntry = MatrixEntry+  { ghc :: GhcEntry+  , packages :: [Package]+  }+  deriving stock (Eq, Show)++-- | The project.+data Project = Project+  { packages :: [Package]+  -- ^ All local packages.+  , matrix :: [MatrixEntry]+  -- ^ In version order.+  , imports :: [Import]+  -- ^ In all conditional blocks.+  }+  deriving stock (Eq, Show)++-- | An @import:@ line of @cabal.project@.+data Import = Import+  { location :: String+  -- ^ The prefix of the error messages, with the file and the position.+  , target :: String+  }+  deriving stock (Eq, Show)++-- | An entry of a @packages:@ or @optional-packages:@ field.+data PackageEntry = PackageEntry+  { location :: String+  -- ^ The prefix of the error messages, with the file and the position.+  , target :: String+  }+  deriving stock (Eq)++-- | A part of @cabal.project@ that the reader uses.+data Part+  = -- | A @packages:@ or @optional-packages:@ field. The flag is true for+    -- @packages:@.+    Packages Bool [PackageEntry]+  | ImportLine Import+  | -- | An @if@ section with its @elif@ and @else@ sections.+    Conditional Position (Condition ConfVar) [Part] [Part]++-- | Read the project in a directory.+readProject+  :: FilePath+  -- ^ The root of the repository.+  -> FilePath+  -- ^ The project directory, relative to the root.+  -> IO (Either [String] Project)+readProject root dir = runExceptT $ do+  exists <- lift $ doesFileExist (root </> projectFile)+  ExceptT . linkErrors root $ [("The project file " ++ projectFile, projectFile) | exists]+  parts <- ExceptT $ readParts exists+  found <- ExceptT $ locatePackages parts+  let cabalFiles = L.nub (concatMap snd found)+  when (null cabalFiles) $+    throwE ["There are no packages in " ++ projectDescription exists dir ++ "."]+  ExceptT . linkErrors root $+    [("The package file " ++ inProject dir f, inProject dir f) | f <- cabalFiles]+  packages <-+    ExceptT $+      runCheck . traverse fromErrors+        <$> forM cabalFiles (\f -> readPackage root (inProject dir f) f)+  except . runCheck $ projectFrom exists dir packages (byToken found packages) parts+  where+    projectFile :: FilePath+    projectFile = inProject dir "cabal.project"++    readParts :: Bool -> IO (Either [String] [Part])+    readParts = \case+      True -> parseProjectFile projectFile <$> BS.readFile (root </> projectFile)+      False ->+        doesDirectoryExist (root </> dir) >>= \case+          True ->+            parentProject <&> \case+              -- The entry has no position in a file, so it is optional, and a+              -- project without packages gets the error for an empty project.+              Nothing ->+                Right [Packages False [PackageEntry {location = "", target = "./*.cabal"}]]+              Just file ->+                Left+                  [ "The project directory "+                      ++ show dir+                      ++ " has no cabal.project, so cabal uses "+                      ++ file+                      ++ " of a parent directory, but the tool reads only the packages of the project directory. Give the directory of "+                      ++ file+                      ++ " to --project-dir, or add a cabal.project to "+                      ++ show dir+                      ++ "."+                  ]+          False -> pure $ Left ["The project directory " ++ show dir ++ " does not exist."]++    -- The nearest cabal.project above the project directory, up to the root.+    -- cabal looks for it from the physical working directory, so the search+    -- starts from the target of a symbolic link. A file above the root does not+    -- count, because the runner has only the repository.+    parentProject :: IO (Maybe FilePath)+    parentProject = do+      top <- canonicalizePath root+      start <- canonicalizePath (root </> dir)+      let parents =+            takeWhile (\p -> splitDirectories top `L.isPrefixOf` splitDirectories p) $+              L.unfoldr+                (\p -> let q = takeDirectory p in if q == p then Nothing else Just (q, q))+                start+      fmap (normalise . (</> "cabal.project") . makeRelative top) . listToMaybe+        <$> filterM (doesFileExist . (</> "cabal.project")) parents++    -- The .cabal files of each entry of packages:, relative to the project+    -- directory.+    locatePackages :: [Part] -> IO (Either [String] [(String, [FilePath])])+    locatePackages parts = do+      locations <- forM (L.nub (allEntries parts)) $ \(required, e) ->+        (e.target,) <$> findPackages root dir required e+      pure . runCheck $ traverse (\(t, r) -> (t,) <$> fromErrors r) locations++    -- A package is known by its directory. If two .cabal files in one directory+    -- are listed by name, both entries give the first package. Such a layout is+    -- rare, so the tool accepts this.+    byToken :: [(String, [FilePath])] -> [Package] -> String -> [Package]+    byToken found packages t =+      [ p+      | f <- concat (lookup t found)+      , Just p <- [L.find (\p -> p.directory == takeDirectory f) packages]+      ]++    allEntries :: [Part] -> [(Bool, PackageEntry)]+    allEntries = concatMap $ \case+      Packages required es -> map (required,) es+      ImportLine _ -> []+      Conditional _ _ yes no -> allEntries yes ++ allEntries no++projectDescription :: Bool -> FilePath -> String+projectDescription exists dir =+  if exists then inProject dir "cabal.project" else "the implicit project of " ++ show dir++-- | A path in the project directory, relative to the root, e.g. @cabal.project@+-- and not @./cabal.project@ for the project directory @.@.+inProject :: FilePath -> FilePath -> FilePath+inProject dir path = normalise (dir </> path)++----------------------------------------+-- cabal.project++-- | Parse @cabal.project@.+parseProjectFile :: FilePath -> BS.ByteString -> Either [String] [Part]+parseProjectFile file input = case readFields input of+  Left e ->+    let pos = errorPos e+    in Left+         [ parserError . PError (Position (sourceLine pos) (sourceColumn pos)) $+             -- The words of the Show instance of ParseError.+             showErrorMessages+               "or"+               "unknown parse error"+               "expecting"+               "unexpected"+               "end of input"+               (errorMessages e)+         ]+  Right fields -> runCheck $ parts fields+  where+    parts :: [Field Position] -> Check [Part]+    parts = \case+      [] -> pure []+      Field (Name pos n) ls : rest+        | n == "packages" -> (:) (Packages True (fieldEntries ls)) <$> parts rest+        | n == "optional-packages" -> (:) (Packages False (fieldEntries ls)) <$> parts rest+        | n == "import" ->+            let i = Import {location = at pos "", target = unwords (map (.target) (fieldEntries ls))}+            in (:) (ImportLine i) <$> parts rest+        | otherwise -> parts rest+      Section (Name pos n) args body : rest+        | n == "if" -> conditional pos args body rest+        | n `elem` ["elif", "else"] ->+            failure (at pos $ BS8.unpack n ++ " without if") *> parts rest+        | otherwise -> parts rest++    -- The elif and else sections that follow an if section. ApplicativeDo joins+    -- the independent statements with <*>, so the errors of the condition and+    -- of the sections come back together.+    conditional+      :: Position+      -> [SectionArg Position]+      -> [Field Position]+      -> [Field Position]+      -> Check [Part]+    conditional pos args body rest = case rest of+      Section (Name pos' "elif") args' body' : rest' -> do+        c <- condition pos args+        yes <- parts body+        -- The elif section is the first part of the result.+        elif <- conditional pos' args' body' rest'+        pure $ case elif of+          p : others -> Conditional pos c yes [p] : others+          [] -> [Conditional pos c yes []]+      Section (Name _ "else") _ body' : rest' -> do+        c <- condition pos args+        yes <- parts body+        no <- parts body'+        others <- parts rest'+        pure $ Conditional pos c yes no : others+      _ -> do+        c <- condition pos args+        yes <- parts body+        others <- parts rest+        pure $ Conditional pos c yes [] : others++    condition :: Position -> [SectionArg Position] -> Check (Condition ConfVar)+    condition pos = fromErrors . first (map parserError) . parseCondition pos++    at :: Position -> String -> String+    at pos msg = showPError file (PError pos msg)++    -- A message of parsec starts with a line break and has a line for each kind+    -- of message.+    parserError :: PError -> String+    parserError (PError pos msg) =+      at pos (L.intercalate ", " . lines $ dropWhile (== '\n') msg)++    -- Split the value of a packages: field into its entries, as cabal does. An+    -- entry can continue on the next line, so the split runs on the joined+    -- lines, and the offset of an entry in them gives its position.+    fieldEntries :: [FieldLine Position] -> [PackageEntry]+    fieldEntries ls =+      [ PackageEntry {location = at (position i) "", target = t}+      | (i, t) <- tokens 0 (unwords texts)+      ]+      where+        texts :: [String]+        texts = [T.unpack (T.decodeUtf8Lenient l) | FieldLine _ l <- ls]++        -- The offset of each line in the joined lines, with its position.+        starts :: [(Int, Position)]+        starts = zip (scanl (\o t -> o + length t + 1) 0 texts) [p | FieldLine p _ <- ls]++        position :: Int -> Position+        position i = case reverse (takeWhile ((<= i) . fst) starts) of+          [] -> zeroPos+          (o, Position row col) : _ -> Position row (col + i - o)++        tokens :: Int -> String -> [(Int, String)]+        tokens i s =+          let (skipped, s') = span separator s+              i' = i + length skipped+          in case s' of+               [] -> []+               '"' : _ | [(t, rest)] <- reads s' -> (i', t) : tokens (i' + length s' - length rest) rest+               _ -> let (t, rest) = token 0 s' in (i', t) : tokens (i' + length t) rest++        token :: Int -> String -> (String, String)+        token depth = \case+          c : cs+            | depth == 0 && separator c -> ("", c : cs)+            | otherwise ->+                let depth' = case c of '{' -> depth + 1; '}' -> max 0 (depth - 1); _ -> depth+                    (t, rest) = token depth' cs+                in (c : t, rest)+          [] -> ("", "")++        separator :: Char -> Bool+        separator c = isSpace c || c == ','++----------------------------------------+-- Package locations++-- | A path that a package location gives.+data LocationMatch+  = -- | A @.cabal@ file, relative to the project directory.+    MatchCabalFile FilePath+  | -- | A package that cabal reads and the tool does not support, with the+    -- error.+    MatchUnsupported String+  | -- | A path without a package, with the error.+    MatchNoPackage String++-- | Find the @.cabal@ files of an entry of @packages:@. The paths are relative+-- to the project directory.+findPackages+  :: FilePath+  -- ^ The root of the repository.+  -> FilePath+  -- ^ The project directory, relative to the root.+  -> Bool+  -> PackageEntry+  -> IO (Either [String] [FilePath])+findPackages root projectDir required entry+  | isUrl t =+      pure $+        Left+          [ at $+              "the package location " ++ show t ++ " is a URL. The tool supports only local packages."+          ]+  | isAbsolute t = notRelative+  -- A glob component other than .. does not lead up, so the location itself+  -- decides for all its matches.+  | leadsOut (projectDir </> t) =+      pure $+        Left+          [ at $+              "the package location "+                ++ show t+                ++ " is not in the repository. The tool supports only packages in the repository."+          ]+  | otherwise = case simpleParsec @RootedGlob t of+      Just (RootedGlob FilePathRelative glob) -> do+        matches <- matchPackageGlob dir glob+        if null matches+          then pure $ missing (if literal glob then "does not exist" else "matches no files")+          else collect <$> mapM classify matches+      -- A glob from the root or the home directory.+      Just _ -> notRelative+      -- As in cabal, a location of packages: that is not a glob can still be a+      -- path, but a location of optional-packages: must be a glob.+      Nothing+        | required -> do+            exists <- (||) <$> doesFileExist (dir </> t) <*> doesDirectoryExist (dir </> t)+            if exists+              then collect . pure <$> classify t+              else pure $ missing "is not a valid glob, and no file or directory has this path"+        | otherwise ->+            pure $ Left [at $ "the package location " ++ show t ++ " is not a valid glob."]+  where+    t :: String+    t = entry.target++    -- An entry without a position starts the message itself.+    at :: String -> String+    at msg = case msg of+      c : cs | null entry.location -> toUpper c : cs+      _ -> entry.location ++ msg++    missing :: String -> Either [String] [FilePath]+    missing reason+      | required = Left [at $ "the package location " ++ show t ++ " " ++ reason ++ "."]+      | otherwise = Right []++    -- A glob without a wildcard or a union names one path.+    literal :: Glob -> Bool+    literal = \case+      GlobDir pieces rest -> all literalPiece pieces && literal rest+      GlobDirRecursive _ -> False+      GlobFile pieces -> all literalPiece pieces+      GlobDirTrailing -> True++    dir :: FilePath+    dir = root </> projectDir++    -- The workflow uses the path on the runner, where it does not exist.+    notRelative :: IO (Either [String] [FilePath])+    notRelative =+      pure $+        Left+          [ at $+              "the package location "+                ++ show t+                ++ " is not a relative path. The tool supports only packages in the repository."+          ]++    -- As in cabal, a path without a package is an error only if no path of the+    -- location has a package, so the glob */ can match a directory with+    -- documentation next to the packages. In optional-packages: it is never an+    -- error (checkIsFileGlobPackage in+    -- cabal-install/src/Distribution/Client/ProjectConfig.hs).+    collect :: [LocationMatch] -> Either [String] [FilePath]+    collect matches = case [e | MatchUnsupported e <- matches] of+      [] -> case [f | MatchCabalFile f <- matches] of+        []+          | required -> Left [e | MatchNoPackage e <- matches]+          | otherwise -> Right []+        files -> Right files+      errors -> Left errors++    classify :: FilePath -> IO LocationMatch+    classify path = do+      isDir <- doesDirectoryExist (dir </> path)+      if isDir+        then do+          -- cabal searches the directory with the glob *.cabal, which skips a+          -- hidden file, e.g. the lock file .#a.cabal of Emacs.+          cabalFiles <-+            filter (\f -> takeExtension f == ".cabal" && not ("." `L.isPrefixOf` f))+              <$> listDirectory (dir </> path)+          pure $ case cabalFiles of+            [f] -> MatchCabalFile (collapse $ path </> f)+            [] -> MatchNoPackage . at $ "the directory " ++ show path ++ " contains no .cabal file."+            _ ->+              MatchNoPackage . at $+                "the directory " ++ show path ++ " contains more than one .cabal file."+        else pure $ case () of+          _+            | ".tar.gz" `L.isSuffixOf` path ->+                MatchUnsupported . at $+                  "the package location "+                    ++ show path+                    ++ " is a tarball. The tool supports only local packages."+            | takeExtension path == ".cabal" -> MatchCabalFile (collapse path)+            | otherwise ->+                MatchNoPackage . at $+                  "the package location " ++ show path ++ " is not a directory or a .cabal file."++    -- Remove each component that a .. after it cancels, so that two paths of+    -- one package, e.g. b and a/../b, give the same path. A .. at the start+    -- stays.+    collapse :: FilePath -> FilePath+    collapse = joinPath . reverse . foldl' step [] . splitDirectories . normalise+      where+        step :: [FilePath] -> FilePath -> [FilePath]+        step acc = \case+          "." -> acc+          ".." | c : rest <- acc, c /= ".." -> rest+          c -> c : acc++----------------------------------------+-- Packages++-- | Read a @.cabal@ file.+readPackage+  :: FilePath+  -- ^ The root of the repository.+  -> FilePath+  -- ^ The path relative to the root.+  -> FilePath+  -- ^ The path relative to the project directory.+  -> IO (Either [String] Package)+readPackage root path relative = do+  input <- BS.readFile (root </> path)+  case runCabalParser path (parseGenericPackageDescription input) of+    Left errors -> pure $ Left errors+    Right gpd -> packageFrom gpd <$> doctestArguments (flattenPackageDescription gpd)+  where+    packageFrom :: GenericPackageDescription -> [[String]] -> Either [String] Package+    packageFrom gpd args = case [r | (GHC, r) <- testedWith pd] of+      [] -> Left ["Package " ++ pkgName' ++ " has no GHC version in tested-with."]+      r : rs ->+        Right+          Package+            { name = pkgName'+            , directory = takeDirectory relative+            , ghcRange = foldl' unionVersionRanges r rs+            , hasTestSuite = not (null (condTestSuites gpd))+            , doctestArgs = args+            }+      where+        pd :: PackageDescription+        pd = packageDescription gpd++        pkgName' :: String+        pkgName' = unPackageName (pkgName (package pd))++    -- The arguments are the language, the extensions and the sources, as in+    -- haskell-ci. The description is flattened, so the fields of all+    -- conditional blocks count.+    doctestArguments :: PackageDescription -> IO [[String]]+    doctestArguments pd = fmap (L.nub . filter (not . null)) . forM (toList (library pd) ++ subLibraries pd) $ \lib -> do+      let bi = libBuildInfo lib+          dirs = map (normalisePath . Path.getSymbolicPath) (hsSourceDirs bi)+      -- The package directory can also contain other components, e.g. the+      -- tests, so it gives the files of the exposed modules instead.+      sources <- fmap concat . forM (if null dirs then ["."] else L.nub dirs) $ \case+        "." -> catMaybes <$> mapM findModuleFile (exposedModules lib)+        dir -> pure [dir]+      pure $+        if null sources+          then []+          else+            ["-X" ++ prettyShow l | Just l <- [defaultLanguage bi]]+              ++ ["-X" ++ prettyShow e | e <- defaultExtensions bi]+              ++ sources++    -- The file of a module in the package directory. For a module name, GHC+    -- takes the compiled module from the GHC environment file, and doctest+    -- finds no examples.+    findModuleFile :: ModuleName.ModuleName -> IO (Maybe FilePath)+    findModuleFile m =+      listToMaybe+        <$> filterM+          (doesFileExist . ((root </> takeDirectory path) </>))+          [ModuleName.toFilePath m <.> ext | ext <- ["hs", "lhs"]]++----------------------------------------+-- Matrix++-- | Make the project from its packages and parts.+projectFrom+  :: Bool+  -- ^ Whether @cabal.project@ exists.+  -> FilePath+  -> [Package]+  -> (String -> [Package])+  -- ^ The packages of an entry of @packages:@.+  -> [Part]+  -> Check Project+projectFrom exists dir packages byToken parts = do+  entries <- traverse (\p -> fromErrors $ entriesFromRange p.name p.ghcRange) packages+  let axis = L.sort (L.nub (concat entries))+  matrix <- dedupe (traverse matrixEntry axis)+  traverse_ (untested matrix) (zip packages entries)+  pure Project {packages = packages, matrix = matrix, imports = imports parts}+  where+    imports :: [Part] -> [Import]+    imports = concatMap $ \case+      Packages _ _ -> []+      ImportLine i -> [i]+      Conditional _ _ yes no -> imports yes ++ imports no++    matrixEntry :: GhcEntry -> Check MatrixEntry+    matrixEntry entry = do+      pkgs <- L.nubBy (\a b -> a.directory == b.directory) <$> included entry parts+      if null pkgs+        then+          failure $+            "There are no packages in "+              ++ projectDescription exists dir+              ++ " for GHC "+              ++ T.unpack (entryText entry)+              ++ "."+        else traverse_ (supports entry) pkgs+      pure (MatrixEntry entry pkgs)++    included :: GhcEntry -> [Part] -> Check [Package]+    included entry =+      fmap concat+        . traverse+          ( \case+              Packages _ es -> pure (concatMap (byToken . (.target)) es)+              ImportLine _ -> pure []+              Conditional pos c yes no -> do+                b <- evaluate entry pos c+                included entry (if b then yes else no)+          )++    supports :: GhcEntry -> Package -> Check ()+    supports entry p = case decide p.ghcRange entry of+      Included -> pure ()+      -- The package lists exact versions of a series that another package lists+      -- as a whole. A condition that includes the exact entries includes a part+      -- of the series entry too, so no block can help.+      Partial ->+        failure $+          "Package "+            ++ p.name+            ++ " lists only some versions of the GHC series "+            ++ T.unpack (entryText entry)+            ++ " in tested-with, but another package lists the whole series. A conditional block in cabal.project cannot separate the two. Write the series in the same form in all packages, e.g. ^>= "+            ++ T.unpack (entryText entry)+            ++ " or exact versions."+      Excluded ->+        failure $+          unlines+            [ "Package "+                ++ p.name+                ++ " does not list GHC "+                ++ T.unpack (entryText entry)+                ++ " in tested-with, but "+                ++ projectDescription exists dir+                ++ " includes it for that GHC version. Move the package to a conditional block in cabal.project, e.g.:"+            , ""+            , "if impl(ghc " ++ prettyShow p.ghcRange ++ ")"+            , "  packages: " ++ p.directory+            ]++    -- A package that some jobs build must be in the project for each version of+    -- its tested-with field, or no job tests that version. A package that no+    -- job builds, e.g. one only for Windows, is out of scope.+    untested :: [MatrixEntry] -> (Package, [GhcEntry]) -> Check ()+    untested matrix (p, own)+      | not (any builds matrix) = pure ()+      | otherwise =+          sequenceA_+            [ failure $+                "Package "+                  ++ p.name+                  ++ " lists GHC "+                  ++ T.unpack (entryText e.ghc)+                  ++ " in tested-with, but "+                  ++ projectDescription exists dir+                  ++ " does not include the package for that GHC version, so no job tests it. Remove the version from tested-with, or change the conditional block in cabal.project."+            | e <- matrix+            , e.ghc `elem` own+            , not (builds e)+            ]+      where+        builds :: MatrixEntry -> Bool+        builds e = p.directory `elem` map (.directory) e.packages++    -- The same error for several matrix entries is shown once.+    dedupe :: Check a -> Check a+    dedupe c = either (fromErrors . Left . L.nub) pure (runCheck c)++    evaluate :: GhcEntry -> Position -> Condition ConfVar -> Check Bool+    evaluate entry pos = \case+      Var (Impl GHC r) ->+        fromEither $+          decideRange (location pos ++ "the condition impl(ghc " ++ prettyShow r ++ ")") r entry+      Var (Impl _ _) -> pure False+      Var (OS os) -> pure (os == Linux)+      Var (Arch arch) -> pure (arch == X86_64)+      Var (PackageFlag f) ->+        failure $+          location pos+            ++ "the condition flag("+            ++ unFlagName f+            ++ ") is not supported, because the tool does not know the value of the flag."+      Lit b -> pure b+      CNot c -> not <$> evaluate entry pos c+      COr a b -> absorb True (evaluate entry pos a) (evaluate entry pos b)+      CAnd a b -> absorb False (evaluate entry pos a) (evaluate entry pos b)++    -- If one side of || is true or one side of && is false, cabal ignores the+    -- other side, so an error in it does not count.+    absorb :: Bool -> Check Bool -> Check Bool -> Check Bool+    absorb z a b+      | Right z `elem` [runCheck a, runCheck b] = pure z+      | otherwise = (if z then (||) else (&&)) <$> a <*> b++    location :: Position -> String+    location pos = showPError (inProject dir "cabal.project") (PError pos "")
+ src/HaskellGha/Project/Compat.hs view
@@ -0,0 +1,91 @@+{-# LANGUAGE CPP #-}++-- | Functions whose Cabal or Cabal-syntax API differs between versions.+module HaskellGha.Project.Compat+  ( -- * Parsing+    runCabalParser+  , parseCondition++    -- * Globs+  , matchPackageGlob+  , literalPiece+  ) where++import Data.Bifunctor+import Data.Foldable+import Distribution.Fields+import Distribution.Fields.ConfVar+import Distribution.Parsec+import Distribution.Simple.Glob+import Distribution.Simple.Glob.Internal+import Distribution.Types.Condition+import Distribution.Types.ConfVar++#if !MIN_VERSION_Cabal(3,18,0)+import System.FilePath+#endif++-- | Whether a piece of a glob has no wildcard.+literalPiece :: GlobPiece -> Bool+literalPiece = \case+  Literal _ -> True+  _ -> False++#if MIN_VERSION_Cabal(3,18,0)+-- | Match a glob of @packages:@ in a directory, as cabal does.+matchPackageGlob :: FilePath -> Glob -> IO [FilePath]+matchPackageGlob = matchGlob+#else+-- | Match a glob of @packages:@ in a directory, as cabal does. Before Cabal+-- 3.18, a wildcard such as @.*@ also matches the entries @.@ and @..@ of a+-- directory, so a match can lead out of the directory.+matchPackageGlob :: FilePath -> Glob -> IO [FilePath]+matchPackageGlob root glob = filter (allowed glob . splitDirectories) <$> matchGlob root glob+  where+    -- A literal component, e.g. the location ., can still be . or .., so only a+    -- component with a wildcard is checked.+    allowed :: Glob -> [FilePath] -> Bool+    allowed g cs = case (g, cs) of+      (GlobDir pieces rest, c : cs') -> component pieces c && allowed rest cs'+      (GlobFile pieces, [c]) -> component pieces c+      _ -> True++    component :: [GlobPiece] -> FilePath -> Bool+    component pieces c = all literalPiece pieces || c `notElem` [".", ".."]+#endif++#if MIN_VERSION_Cabal_syntax(3,18,0)+-- | Run a parser of Cabal-syntax. The result has the rendered errors.+runCabalParser+  :: FilePath+  -- ^ The file name for the error messages.+  -> ParseResult src a+  -> Either [String] a+runCabalParser file = first (map (showPError file)) . parserErrors++-- | Parse the condition of an @if@ or @elif@ section.+parseCondition :: Position -> [SectionArg Position] -> Either [PError] (Condition ConfVar)+parseCondition pos = parserErrors . parseConditionConfVar pos++parserErrors :: ParseResult src a -> Either [PError] a+parserErrors p = case snd (runParseResult p) of+  Right a -> Right a+  Left (_, errors) -> Left [e | PErrorWithSource _ e <- toList errors]+#else+-- | Run a parser of Cabal-syntax. The result has the rendered errors.+runCabalParser+  :: FilePath+  -- ^ The file name for the error messages.+  -> ParseResult a+  -> Either [String] a+runCabalParser file = first (map (showPError file)) . parserErrors++-- | Parse the condition of an @if@ or @elif@ section.+parseCondition :: Position -> [SectionArg Position] -> Either [PError] (Condition ConfVar)+parseCondition _ = parserErrors . parseConditionConfVar++parserErrors :: ParseResult a -> Either [PError] a+parserErrors p = case snd (runParseResult p) of+  Right a -> Right a+  Left (_, errors) -> Left (toList errors)+#endif
+ src/HaskellGha/Project/Ghc.hs view
@@ -0,0 +1,176 @@+-- | The entries of the @ghc@ axis of the matrix.+module HaskellGha.Project.Ghc+  ( -- * Entries+    GhcEntry (..)+  , entryRange+  , entryText+  , entriesFromRange++    -- * Decisions+  , Decision (..)+  , decide+  , decideRange+  ) where++import Control.Monad+import Data.Either+import Data.Text qualified as T+import Distribution.Pretty+import Distribution.Types.VersionInterval+import Distribution.Version++-- | An entry of the @ghc@ axis.+data GhcEntry+  = -- | An exact version, e.g. @9.10.3@.+    GhcExact Version+  | -- | A major series, e.g. @9.10@. GHCup selects its newest release.+    GhcSeries Int Int+  deriving stock (Eq, Show)++-- | Sort by the lowest version of the entry.+instance Ord GhcEntry where+  compare a b = compare (key a) (key b)+    where+      key :: GhcEntry -> (Version, Bool)+      key = \case+        GhcSeries x y -> (mkVersion [x, y], False)+        GhcExact v -> (v, True)++-- | The versions that GHCup can select for the entry. The first release of a+-- GHC series is X.Y.1, so a condition such as @impl(ghc >= 9.10.1)@ includes the+-- whole series.+entryRange :: GhcEntry -> VersionRange+entryRange = \case+  GhcExact v -> thisVersion v+  GhcSeries x y ->+    intersectVersionRanges+      (orLaterVersion (mkVersion [x, y, 1]))+      (earlierVersion (mkVersion [x, y + 1]))++-- | The value of the entry in the matrix.+entryText :: GhcEntry -> T.Text+entryText = \case+  GhcExact v -> T.pack (prettyShow v)+  GhcSeries x y -> T.pack (show x ++ "." ++ show y)++-- | Split the GHC range of a package into entries.+entriesFromRange+  :: String+  -- ^ The name of the package for the error messages.+  -> VersionRange+  -> Either [String] [GhcEntry]+entriesFromRange package range = case asVersionIntervals range of+  [] -> Left [emptyRange]+  intervals -> case partitionEithers $ map (entry >=> supported) intervals of+    ([], entries) -> Right entries+    (bad, _) -> Left bad+  where+    emptyRange :: String+    emptyRange =+      "Package "+        ++ package+        ++ " lists the GHC range "+        ++ prettyShow range+        ++ " in tested-with, which includes no version. Join the versions with ||, e.g. ^>= 9.10 || ^>= 9.12."++    -- Nobody tests older versions on the current runner images, which can lack+    -- the system libraries of their bindists.+    supported :: GhcEntry -> Either String GhcEntry+    supported e+      | decide (orLaterVersion (mkVersion [8, 10])) e == Included = Right e+      | otherwise =+          Left $+            "Package "+              ++ package+              ++ " lists GHC "+              ++ T.unpack (entryText e)+              ++ " in tested-with. The tool supports only GHC 8.10 and later. Remove the version from tested-with."++    entry :: VersionInterval -> Either String GhcEntry+    entry i@(VersionInterval lower upper) = case (lower, upper) of+      (LowerBound v InclusiveBound, UpperBound w InclusiveBound)+        | v == w ->+            -- GHCup selects the newest release of the series for such a+            -- version, e.g. 9.10.3 for 9.10.+            if length (versionNumbers v) < 3+              then Left (shortVersion v)+              else Right (GhcExact v)+      (LowerBound v InclusiveBound, UpperBound w ExclusiveBound)+        | [x, y] <- versionNumbers v+        , versionNumbers w == [x, y + 1] ->+            Right (GhcSeries x y)+      (_, NoUpperBound) -> Left (openRange (fromInterval i))+      _ -> Left (partialSeries (fromInterval i))++    openRange :: VersionRange -> String+    openRange r =+      "Package "+        ++ package+        ++ " lists the GHC range "+        ++ prettyShow r+        ++ " in tested-with. The matrix needs a finite list of versions. Write an exact version, e.g. == 9.10.3, or a major series, e.g. ^>= 9.10."++    partialSeries :: VersionRange -> String+    partialSeries r =+      "Package "+        ++ package+        ++ " lists the GHC range "+        ++ prettyShow r+        ++ " in tested-with. A range must be a whole major series with two version parts, e.g. ^>= 9.10 or == 9.10.*. Write the series, or an exact version, e.g. == 9.10.3."++    shortVersion :: Version -> String+    shortVersion v =+      "Package "+        ++ package+        ++ " lists GHC == "+        ++ prettyShow v+        ++ " in tested-with. No GHC release has this version. Write an exact version with three parts, e.g. == 9.10.3, or a major series, e.g. ^>= 9.10."++    fromInterval :: VersionInterval -> VersionRange+    fromInterval (VersionInterval (LowerBound v lb) upper) =+      let lowerRange = case lb of+            InclusiveBound -> orLaterVersion v+            ExclusiveBound -> laterVersion v+      in case upper of+           NoUpperBound -> lowerRange+           UpperBound w ub ->+             intersectVersionRanges lowerRange $ case ub of+               InclusiveBound -> orEarlierVersion w+               ExclusiveBound -> earlierVersion w++-- | The result of a range for a matrix entry.+data Decision+  = -- | The range includes all versions of the entry.+    Included+  | -- | The range includes no version of the entry.+    Excluded+  | -- | The range includes only a part of the entry.+    Partial+  deriving stock (Eq, Show)++-- | Decide a range for a matrix entry.+decide :: VersionRange -> GhcEntry -> Decision+decide range entry+  | null common = Excluded+  | common == asVersionIntervals (entryRange entry) = Included+  | otherwise = Partial+  where+    common :: [VersionInterval]+    common = asVersionIntervals (intersectVersionRanges range (entryRange entry))++-- | Decide a range for a matrix entry. A partial result is an error.+decideRange+  :: String+  -- ^ A description of the range for the error message.+  -> VersionRange+  -> GhcEntry+  -> Either String Bool+decideRange description range entry = case decide range entry of+  Included -> Right True+  Excluded -> Right False+  Partial ->+    Left $+      description+        ++ " includes only a part of the GHC versions of the matrix entry "+        ++ T.unpack (entryText entry)+        ++ ", so the result depends on the minor version that GHCup selects. Change the range, or write exact versions in tested-with."
+ src/HaskellGha/Workflow.hs view
@@ -0,0 +1,625 @@+-- The lists of the workflow join their parts with concat, also if there are+-- only two parts.+{- HLINT ignore "Use ++" -}++-- | The generated workflow.+module HaskellGha.Workflow+  ( -- * Workflow+    workflow+  ) where++import Data.Functor+import Data.List qualified as L+import Data.Maybe+import Data.Text qualified as T+import Distribution.Pretty+import Distribution.Version+import System.FilePath+import Yamlet+import Yamlet.Syntax++import HaskellGha.Check+import HaskellGha.Command.Options+import HaskellGha.Config+import HaskellGha.Path+import HaskellGha.Project+import HaskellGha.Project.Ghc+import HaskellGha.Workflow.Script+import HaskellGha.Workflow.Validate+import HaskellGha.Yaml++-- | Generate the workflow.+workflow :: Options -> ConfigSource -> Config -> Project -> Either [String] Node+workflow opts source config project =+  runCheck $ validateWorkflow opts source config project stepIds $> root+  where+    stepIds :: [T.Text]+    stepIds = [i.value | s <- setupSteps ++ buildSteps ++ testSteps, Just i <- [stringField "id" s]]++    entries :: [GhcEntry]+    entries = map (.ghc) project.matrix++    fromTarballs :: Bool+    fromTarballs = config.buildFrom == BuildFromTarballs++    root :: Node+    root =+      mapping+        [ "name" .= copied config.name+        , -- GitHub reads a plain on as a string, so the key needs no quotes,+          -- although YAML 1.1 reads it as a boolean.+          (plain "on", triggers)+        , "permissions" .= copied config.permissions+        , -- A new run cancels the older run of the same ref, also on a branch+          -- of the push trigger. The newer run tests the newer code and saves+          -- the cache that the older run did not save. The workflow_ref has the+          -- path of the workflow file and the ref, so two workflows with the+          -- same name do not share the group.+          "concurrency"+            .= mapping+              [ "group" .= plain "${{ github.workflow_ref }}"+              , "cancel-in-progress" .= True+              ]+        , "defaults"+            .= mapping+              [ "run"+                  .= mappingConcat+                    [ ["shell" .= plain "bash"]+                    , workingDirectory+                    ]+              ]+        , -- The short jobs come first, so the long build job does not hide+          -- them.+          "jobs"+            .= mappingConcat+              [ ["fourmolu" .= fourmoluJob f | Just f <- [config.fourmolu.value]]+              , ["hlint" .= hlintJob h | Just h <- [config.hlint.value]]+              , ["build" .= job]+              ]+        ]++    mappingConcat :: [[(Node, Node)]] -> Node+    mappingConcat = mapping . concat++    copied :: Commented a -> Commented a+    copied c = Commented c.value c.comments {before = directlyAbove c.comments.before}++    -- A comment above an empty line describes the layout of the configuration,+    -- e.g. a section of it, and the workflow has its own layout.+    directlyAbove :: [Line] -> [Line]+    directlyAbove = reverse . takeWhile (/= EmptyLine) . reverse++    triggers :: Node+    triggers =+      mapping+        [ "push" .= mapping ["branches" .= copied config.branches]+        , "pull_request" .= nullValue+        , "merge_group" .= nullValue+        , "workflow_dispatch" .= nullValue+        ]++    workingDirectory :: [(Node, Node)]+    workingDirectory = ["working-directory" .= plain (T.pack projectDir) | projectDir /= "."]++    projectDir :: FilePath+    projectDir = normalisePath opts.projectDir++    job :: Node+    job =+      mappingConcat+        [+          [ "name" .= jobName+          , runsOn (Just config.runsOn)+          ]+        , ["container" .= plain c.image | Just c <- [config.container.value]]+        , [timeout]+        , ["services" .= copied s | Just s <- [config.services.value]]+        ,+          [ "strategy"+              .= mapping+                [ "fail-fast" .= False+                , "matrix" .= copied (Commented matrix config.matrix.comments)+                ]+          ]+        , ["steps" .= steps]+        ]++    -- A job without its own runs-on gets the value of the top-level key, but+    -- the comments of that key stay with the build job.+    runsOn :: Maybe (Commented RunsOn) -> (Node, Node)+    runsOn = \case+      Just r -> "runs-on" .= copied r+      Nothing -> "runs-on" .= config.runsOn.value++    timeout :: (Node, Node)+    timeout = "timeout-minutes" .= config.timeoutMinutes.value++    -- The job needs no GHC, so it runs once, next to the build jobs.+    fourmoluJob :: Fourmolu -> Node+    fourmoluJob f =+      mapping+        [ "name" .= plain "Fourmolu"+        , runsOn f.runsOn.value+        , timeout+        , "steps"+            .= sequenceNode+              [ checkoutStep NoSubmodules+              , mapping+                  [ uses "haskell-actions/run-fourmolu" "" config.actions.runFourmolu+                  , "with"+                      .= mappingConcat+                        [ ["version" .= singleQuoted (T.pack (prettyShow f.version))]+                        , ["pattern" .= literal (T.unlines (map (.value) f.patterns)) | not (null f.patterns)]+                        , -- The run defaults do not apply to an action.+                          workingDirectory+                        ]+                  ]+              ]+        ]++    hlintJob :: HLint -> Node+    hlintJob h =+      mapping+        [ "name" .= plain "HLint"+        , runsOn h.runsOn.value+        , timeout+        , "steps"+            .= sequenceNode+              [ checkoutStep NoSubmodules+              , mapping+                  [ uses "haskell-actions/hlint-setup" "" config.actions.hlintSetup+                  , "with" .= mapping ["version" .= singleQuoted (T.pack (prettyShow h.version))]+                  ]+              , mapping+                  [ uses "haskell-actions/hlint-run" "" config.actions.hlintRun+                  , "with"+                      .= mappingConcat+                        [ ["path" .= p | Just p <- [hlintPath h]]+                        , ["fail-on" .= h.failOn]+                        ]+                  ]+              ]+        ]++    -- The action runs in the root of the repository and takes one path, or a+    -- JSON array of paths. Without a path, it checks the root.+    hlintPath :: HLint -> Maybe Node+    hlintPath h = case paths of+      ["."] -> Nothing+      [p] -> Just (singleQuoted (T.pack p))+      ps -> Just (singleQuoted ("[" <> T.intercalate ", " (map (jsonString . T.pack) ps) <> "]"))+      where+        paths :: [FilePath]+        paths+          | null h.paths = [projectDir]+          | otherwise =+              [ normalisePath (projectDir </> T.unpack p.value.value)+              | p <- h.paths+              ]++        jsonString :: T.Text -> T.Text+        jsonString t =+          "\""+            <> T.concatMap (\c -> if c `elem` ['"', '\\'] then T.pack ['\\', c] else T.singleton c) t+            <> "\""++    -- The fourmolu and HLint jobs do not fetch the submodules, because the+    -- files of a submodule are not the code of the project. The token does not+    -- stay in the git config, because the code of a dependency, e.g. a Setup.hs+    -- or Template Haskell, runs later in the job and could read it.+    checkoutStep :: Submodules -> Node+    checkoutStep submodules =+      mapping+        [ uses "actions/checkout" "" config.actions.checkout+        , "with"+            .= mapping+              ( ("persist-credentials" .= False) : case submodules of+                  NoSubmodules -> []+                  TopSubmodules -> ["submodules" .= True]+                  RecursiveSubmodules -> ["submodules" .= plain "recursive"]+              )+        ]++    -- The default repository, and the path of the action in the repository,+    -- e.g. /restore.+    uses :: T.Text -> T.Text -> ActionRef -> (Node, Node)+    uses repo path a = "uses" .= plain (fromMaybe repo a.repository <> path <> "@" <> a.ref)++    jobName :: Node+    jobName = case parts of+      [p] -> plain p+      ps -> singleQuoted (T.intercalate ", " ps)+      where+        -- The values newest and oldest are clear without the axis name.+        parts :: [T.Text]+        parts =+          concat+            [ ["GHC ${{ matrix.ghc }}"]+            , ["${{ matrix.dependencies }}" | bothDependencies]+            , [a <> " ${{ matrix." <> a <> " }}" | a <- map (.value) config.matrix.value.axes]+            ]++    bothDependencies :: Bool+    bothDependencies = config.dependencies == DependenciesBoth++    -- The comments below matrix: and above an empty line describe the whole+    -- matrix, so they stay above the ghc axis. The comments after the matrix+    -- are in its entry, so the entry writes them after the new matrix.+    matrix :: Node+    matrix =+      addBefore (dropWhile (== EmptyLine) config.matrix.value.leading) $+        mappingConcat+          [ ["ghc" .= sequenceNode (map (singleQuoted . entryText) entries)]+          , ["dependencies" .= sequenceNode [plain "newest", plain "oldest"] | bothDependencies]+          , config.matrix.value.entries+          ]++    -- The after-setup hooks come before the tarballs and the build plan, so a+    -- hook can install a library that the build plan needs, and the tarballs+    -- can contain a file that a hook makes.+    steps :: Node+    steps =+      sequenceNode $+        concat+          [ setupSteps+          , map hookStep config.hooks.afterSetup+          , buildSteps+          , map hookStep config.hooks.afterBuild+          , testSteps+          ]+      where+        hookStep :: MappingNode -> Node+        hookStep s = mapBefore directlyAbove s.value++    setupSteps :: [Node]+    setupSteps =+      concat+        [ [checkoutStep config.submodules]+        , [ runStep+              "Install the system packages"+              Nothing+              (aptScript config.container.value config.apt)+          | not (null config.apt)+          ]+        , [ runStep+              "Install the gold linker"+              (Just goldEntries)+              (aptScript config.container.value ["binutils-gold"])+          | not (null goldEntries)+          ]+        , [setupStep]+        , [versionsStep]+        ]++    buildSteps :: [Node]+    buildSteps =+      concat+        [ [ runStep "Unpack the source tarballs" (Just group) (unpackScript pkgs)+          | fromTarballs+          , (group, pkgs) <- packageGroups project.matrix+          ]+        , [configureStep]+        , oldestStep+        , [ sourceStep+              "Enable parallel module builds for the local packages"+              (Just es)+              (parallelScript config.cabalJobs.value)+          | let es = filter (not . hasSemaphore) entries+          , not (null es)+          ]+        , [ sourceStep+              "Enable the GHC job semaphore or parallel module builds"+              (Just es)+              (semaphoreScript config.cabalJobs.value config.cabalVersion)+          | let es = filter hasSemaphore entries+          , not (null es)+          ]+        , [planStep]+        , [cacheRestore]+        , [sourceStep "Build the dependencies" Nothing "cabal build all --only-dependencies\n"]+        , [cacheSave]+        , concat [doctestSteps d | not (null doctestEntries), Just d <- [config.doctest.value]]+        , [sourceStep "Build" Nothing "cabal build all\n"]+        ]++    testSteps :: [Node]+    testSteps =+      concat+        [ [ sourceStep+              "Run the tests"+              (Just testEntries)+              "cabal test all --test-show-details=direct\n"+          | config.tests+          , not (null testEntries)+          ]+        , [ sourceStep+              ("Run doctest for " <> T.pack p.name)+              (Just es)+              (doctestScript d.options p)+          | Just d <- [config.doctest.value]+          , p <- project.packages+          , T.pack p.name `notElem` map (.value) d.skipPackages+          , not (null p.doctestArgs)+          , let es =+                  [ e.ghc+                  | e <- project.matrix+                  , e.ghc `elem` doctestEntries+                  , p.directory `elem` map (.directory) e.packages+                  ]+          , not (null es)+          ]+        , [ sourceStep "Check the packages" (Just group) (checkScript pkgs)+          | config.cabalCheck+          , (group, pkgs) <- packageGroups project.matrix+          ]+        , -- With --haddock-all, each component of a package writes the same+          -- documentation tarball, and parallel components then fail on its+          -- file lock.+          [ sourceStep+              "Build the documentation"+              Nothing+              "cabal haddock all --disable-documentation --haddock-for-hackage\n"+          | config.haddock+          ]+        ]++    -- The entries in the range of doctest.ghc. The workflow installs doctest+    -- for such an entry also if no package runs it there, e.g. if+    -- doctest.skip-packages names all packages. Only an unusual configuration+    -- does that, so the tool accepts the extra steps.+    doctestEntries :: [GhcEntry]+    doctestEntries =+      [ e+      | Just d <- [config.doctest.value]+      , e <- entries+      , decide d.ghc.value e == Included+      ]++    -- The key of the main cache does not depend on the doctest version, so+    -- doctest has its own cache with only the binary.+    doctestSteps :: Doctest -> [Node]+    doctestSteps d =+      [ step+          False+          "Find the doctest version"+          (("id" .= plain "doctest") : doctestIf [])+          findDoctest+      , mappingConcat+          [+            [ uses "actions/cache" "/restore" config.actions.cache+            , "id" .= plain "doctest-cache"+            ]+          , doctestIf []+          ,+            [ "with"+                .= mapping+                  [ "path" .= plain "~/.local/bin/doctest"+                  , "key" .= plain cacheKey+                  ]+            ]+          ]+      , step False "Install doctest" (doctestIf [cacheMiss]) installDoctest+      , -- A separate save step keeps the binary also if a later step fails.+        mappingConcat+          [ [uses "actions/cache" "/save" config.actions.cache]+          , doctestIf [cacheMiss]+          ,+            [ "with"+                .= mapping+                  [ "path" .= plain "~/.local/bin/doctest"+                  , "key" .= plain "${{ steps.doctest-cache.outputs.cache-primary-key }}"+                  ]+            ]+          ]+      ]+      where+        cacheMiss :: T.Text+        cacheMiss = "steps.doctest-cache.outputs.cache-hit != 'true'"++        cacheKey :: T.Text+        cacheKey =+          T.intercalate+            "-"+            [ "haskell-gha"+            , cacheVersion+            , "${{ runner.os }}"+            , "${{ runner.arch }}"+            , "${{ steps.versions.outputs.image }}"+            , "doctest"+            , "${{ steps.doctest.outputs.version }}"+            , "ghc"+            , "${{ steps.setup.outputs.ghc-version }}"+            ]++        installDoctest :: T.Text+        installDoctest =+          T.unwords+            [ "cabal install doctest"+            , "--ignore-project"+            , "--install-method=copy"+            , "--installdir=\"$HOME/.local/bin\""+            , "--overwrite-policy=always"+            , "--constraint='doctest ==${{ steps.doctest.outputs.version }}'"+            ]+            <> "\n"++        doctestIf :: [T.Text] -> [(Node, Node)]+        doctestIf = ifField (Just doctestEntries)++        -- A store that already contains doctest gives a plan without it, so the+        -- dry run uses an empty store.+        findDoctest :: T.Text+        findDoctest =+          T.unlines+            [ "version=$(cabal --store-dir=\"$RUNNER_TEMP\"/doctest-store install doctest --ignore-project --dry-run"+                <> maybe+                  ""+                  (\r -> " --constraint=" <> shellQuote ("doctest " <> T.pack (prettyShow r)))+                  d.version.value+                <> " | sed -n 's/^ - doctest-\\([0-9.]*\\) (exe:doctest).*/\\1/p')"+            , "if [ -z \"$version\" ]; then"+            , "  echo 'The dry run of cabal install shows no doctest version.' >&2"+            , "  exit 1"+            , "fi"+            , "echo \"version=$version\" >> \"$GITHUB_OUTPUT\""+            ]++    runStep :: T.Text -> Maybe [GhcEntry] -> T.Text -> Node+    runStep name only = step False name (ifField only [])++    -- A step that runs in the content of the tarballs, if the build uses them.+    sourceStep :: T.Text -> Maybe [GhcEntry] -> T.Text -> Node+    sourceStep name only = step fromTarballs name (ifField only [])++    step :: Bool -> T.Text -> [(Node, Node)] -> T.Text -> Node+    step inSource name fields script =+      mappingConcat+        [ ["name" .= plain name]+        , fields+        , ["working-directory" .= plain ("${{ runner.temp }}/" <> sourceDirName) | inSource]+        , ["run" .= literal script]+        ]++    -- Nothing stands for all matrix entries.+    ifField :: Maybe [GhcEntry] -> [T.Text] -> [(Node, Node)]+    ifField only extra = case [condition es | Just es <- [only], es /= entries] ++ extra of+      [] -> []+      cs -> ["if" .= plain (T.intercalate " && " cs)]++    configureStep :: Node+    configureStep =+      sourceStep+        "Configure the project"+        Nothing+        (configureScript config (not (null doctestEntries)))++    -- hashFiles only reads files in the workspace, and the content of the+    -- tarballs is outside it. Thus the step gives the hash of the plan to the+    -- cache key as an output.+    planStep :: Node+    planStep =+      step fromTarballs "Make the build plan" ["id" .= plain "plan"] $+        T.unlines+          [ "cabal build all --dry-run"+          , "echo \"hash=$(sha256sum dist-newstyle/cache/plan.json | cut -d ' ' -f 1)\" >> \"$GITHUB_OUTPUT\""+          ]++    condition :: [GhcEntry] -> T.Text+    condition es =+      "contains(fromJSON('["+        <> T.intercalate "," ["\"" <> entryText e <> "\"" | e <- es]+        <> "]'), matrix.ghc)"++    setupStep :: Node+    setupStep =+      step+        False+        "Install GHC and cabal"+        ["id" .= plain "setup"]+        (setupScript config.cabalVersion)++    -- An expression cannot read the environment variable ImageOS of the runner,+    -- so the step gives it to the cache key as an output. In a container, the+    -- variable is empty, and the image of the container takes its place.+    versionsStep :: Node+    versionsStep =+      mapping+        [ "name" .= plain "Show the versions"+        , "id" .= plain "versions"+        , "run"+            .= literal+              ( T.unlines+                  [ "ghc --version"+                  , "cabal --version"+                  , "echo \"GHC ${{ steps.setup.outputs.ghc-version }}, cabal ${{ steps.setup.outputs.cabal-version }}, image "+                      <> summaryImage+                      <> "\" >> \"$GITHUB_STEP_SUMMARY\""+                  , "echo \"image=" <> keyImage <> "\" >> \"$GITHUB_OUTPUT\""+                  ]+              )+        ]+      where+        summaryImage, keyImage :: T.Text+        (summaryImage, keyImage) = case config.container.value of+          Nothing -> ("$ImageOS $ImageVersion", "$ImageOS")+          Just c -> (c.image, c.image)++    -- Each later cabal command reads cabal.project.local, so all of them use+    -- the plan with the oldest versions.+    oldestStep :: [Node]+    oldestStep = case config.dependencies of+      DependenciesNewest -> []+      DependenciesOldest -> [preferOldest []]+      DependenciesBoth -> [preferOldest ["matrix.dependencies == 'oldest'"]]+      where+        preferOldest :: [T.Text] -> Node+        preferOldest extra =+          step+            fromTarballs+            "Prefer the oldest dependencies"+            (ifField Nothing extra)+            "echo 'prefer-oldest: True' >> cabal.project.local\n"++    packageGroups :: [MatrixEntry] -> [([GhcEntry], [Package])]+    packageGroups es =+      [ ([e.ghc | e <- es, names e.packages == names pkgs], pkgs)+      | pkgs <- L.nubBy (\a b -> names a == names b) (map (.packages) es)+      ]+      where+        names :: [Package] -> [String]+        names = map (.name)++    -- The semaphore needs GHC 9.8. A matrix entry is an exact version or a+    -- major series, so the range decides each entry completely.+    hasSemaphore :: GhcEntry -> Bool+    hasSemaphore e = decide (orLaterVersion (mkVersion [9, 8])) e == Included++    -- The hsc2hs of GHC 9.4 and older links with gold also if the runner has no+    -- gold, and Ubuntu 25.10 and later do not install gold by default.+    goldEntries :: [GhcEntry]+    goldEntries = [e | e <- entries, decide (earlierVersion (mkVersion [9, 5])) e == Included]++    testEntries :: [GhcEntry]+    testEntries = [e.ghc | e <- project.matrix, any (.hasTestSuite) e.packages]++    cacheRestore :: Node+    cacheRestore =+      mapping+        [ uses "actions/cache" "/restore" config.actions.cache+        , "id" .= plain "cache"+        , "with"+            .= mapping+              [ "path" .= plain "${{ steps.setup.outputs.cabal-store }}"+              , "key" .= plain (cachePrefix <> "${{ steps.plan.outputs.hash }}")+              , "restore-keys" .= plain cachePrefix+              ]+        ]++    -- A new value starts new caches. Change it when the tool makes the content+    -- of an old cache wrong, e.g. when it installs GHC in another way.+    cacheVersion :: T.Text+    cacheVersion = "v1"++    -- A store from another image can link against system libraries that this+    -- image does not have. The prefix is also the restore key, so a job+    -- restores only a store of its own workflow with its own kind of+    -- dependencies. A store of another workflow would be saved again with the+    -- dependencies of both.+    cachePrefix :: T.Text+    cachePrefix =+      T.pack opts.output <> "-" <> cacheVersion <> "-${{ runner.os }}-${{ runner.arch }}-${{ steps.versions.outputs.image }}-ghc-${{ steps.setup.outputs.ghc-version }}-" <> case config.dependencies of+        DependenciesNewest -> "newest-"+        DependenciesOldest -> "oldest-"+        DependenciesBoth -> "${{ matrix.dependencies }}-"++    cacheSave :: Node+    cacheSave =+      mapping+        [ uses "actions/cache" "/save" config.actions.cache+        , "if" .= plain "steps.cache.outputs.cache-hit != 'true'"+        , "with"+            .= mapping+              [ "path" .= plain "${{ steps.setup.outputs.cabal-store }}"+              , "key" .= plain "${{ steps.cache.outputs.cache-primary-key }}"+              ]+        ]
+ src/HaskellGha/Workflow/Script.hs view
@@ -0,0 +1,275 @@+-- | The shell scripts of the workflow steps. A script that refers to a step+-- output stays with its step in "HaskellGha.Workflow", next to the step IDs.+module HaskellGha.Workflow.Script+  ( -- * Quoting+    shellQuote++    -- * Source tarballs+  , sourceDirName+  , unpackScript++    -- * Scripts+  , aptScript+  , setupScript+  , configureScript+  , parallelScript+  , semaphoreScript+  , checkScript+  , doctestScript+  ) where++import Data.Char+import Data.Text qualified as T+import Distribution.Pretty+import Distribution.Version++import HaskellGha.Config+import HaskellGha.Project++-- | Quote a word for bash, if it needs quotes.+shellQuote :: T.Text -> T.Text+shellQuote t+  | not (T.null t) && T.all safe t = t+  | otherwise = "'" <> T.replace "'" "'\\''" t <> "'"+  where+    safe :: Char -> Bool+    safe c = isAsciiLower c || isAsciiUpper c || isDigit c || elem @[] c "-_./=:+@%,"++----------------------------------------+-- Source tarballs++-- | The directory in the temporary directory of the runner with the content of+-- the tarballs, at the same relative paths as in the project directory.+sourceDirName :: T.Text+sourceDirName = "haskell-gha"++-- | Unpack the tarballs of the packages. The step makes the tarballs of the+-- packages of the matrix entry, so a package that is not in the project has no+-- tarball. The pattern of a tarball allows only a version after the name,+-- because the tarball of a package foo-2d also starts with foo-.+unpackScript :: [Package] -> T.Text+unpackScript pkgs =+  T.unlines $+    [ "shopt -s extglob"+    , "cabal sdist all --output-directory=\"$RUNNER_TEMP\"/haskell-gha-sdist"+    , "mkdir " <> sourceDir+    , "for f in cabal.project cabal.project.freeze cabal.project.local; do"+    , "  if [ -f \"$f\" ]; then cp \"$f\" " <> sourceDir <> "; fi"+    , "done"+    ]+      ++ concat+        [ ["mkdir -p " <> dir | p.directory /= "."]+            ++ [ "tar -xzf \"$RUNNER_TEMP\"/haskell-gha-sdist/"+                   <> T.pack p.name+                   <> "-+([0-9.]).tar.gz --strip-components=1 -C "+                   <> dir+               ]+        | p <- pkgs+        , let dir =+                if p.directory == "."+                  then sourceDir+                  else sourceDir <> "/" <> shellQuote (T.pack p.directory)+        ]+  where+    sourceDir :: T.Text+    sourceDir = "\"$RUNNER_TEMP\"/" <> sourceDirName++----------------------------------------+-- Scripts++-- | Install Ubuntu packages. A job in a container runs as root, and the image+-- has no sudo. The runner images set DEBIAN_FRONTEND in /etc/environment, but+-- the containers do not, and a debconf question there waits for an answer on+-- stdin. sudo drops the variable from the environment of the step, so the+-- command line sets it.+aptScript+  :: Maybe Container+  -- ^ The container of the job.+  -> [T.Text]+  -- ^ The packages.+  -> T.Text+aptScript container packages =+  T.unlines+    [ sudo <> "apt-get update"+    , sudo+        <> "DEBIAN_FRONTEND=noninteractive apt-get install -y --no-install-recommends "+        <> T.unwords (map shellQuote packages)+    ]+  where+    sudo :: T.Text+    sudo = maybe "sudo " (const "") container++-- | Install GHCup, and with it GHC and cabal. The runner images set+-- GHCUP_INSTALL_BASE_PREFIX to their own GHCup, so the script sets it to a+-- directory of the job, also for the later steps. The script asks the vanilla+-- channel whether it has the GHC version before it installs it, because GHCup+-- reports a missing version and a failed download with the same exit code. With+-- both channels at once, GHCup picks the newest version of a series, which can+-- be a prerelease of its next release. A line of ghcup list -r starts with+-- "ghc <version> ", so the two patterns match the exact version and a version+-- of the series. cabal path reads the project unless it ignores it, and then+-- it can clone a source-repository-package.+setupScript :: CabalVersion -> T.Text+setupScript (CabalVersion cabal) =+  T.unlines+    [ "mkdir -p \"$RUNNER_TEMP\"/.ghcup/bin"+    , "curl -fsSL -o \"$RUNNER_TEMP\"/.ghcup/bin/ghcup \"https://downloads.haskell.org/ghcup/$(uname -m)-linux-ghcup\""+    , "chmod +x \"$RUNNER_TEMP\"/.ghcup/bin/ghcup"+    , "export GHCUP_INSTALL_BASE_PREFIX=\"$RUNNER_TEMP\" PATH=\"$RUNNER_TEMP/.ghcup/bin:$PATH\""+    , "echo \"GHCUP_INSTALL_BASE_PREFIX=$RUNNER_TEMP\" >> \"$GITHUB_ENV\""+    , "echo \"$RUNNER_TEMP/.ghcup/bin\" >> \"$GITHUB_PATH\""+    , "versions=$(ghcup -s vanilla list -t ghc -r)"+    , "if grep -qF -e 'ghc ${{ matrix.ghc }} ' -e 'ghc ${{ matrix.ghc }}.' <<< \"$versions\"; then"+    , "  channel=vanilla"+    , "else"+    , "  echo 'The vanilla channel of GHCup has no GHC ${{ matrix.ghc }}, so the step uses the prerelease channel.'"+    , "  channel=prereleases"+    , "fi"+    , "ghcup -s \"$channel\" install ghc '${{ matrix.ghc }}' --set"+    , "ghcup -s vanilla install cabal " <> T.pack (prettyShow cabal) <> " --set"+    , "cabal update"+    , "echo \"ghc-version=$(ghc --numeric-version)\" >> \"$GITHUB_OUTPUT\""+    , "echo \"cabal-version=$(cabal --numeric-version)\" >> \"$GITHUB_OUTPUT\""+    , "echo \"cabal-store=$(cabal path -z --store-dir)\" >> \"$GITHUB_OUTPUT\""+    ]++-- | Write the settings of the configuration to @cabal.project.local@. The file+-- holds the settings of one developer, so a committed one is an error. The tool+-- cannot tell it from an uncommitted one, so the job checks the checkout.+configureScript+  :: Config+  -> Bool+  -- ^ Whether doctest runs, so it needs the GHC environment files.+  -> T.Text+configureScript config doctest =+  T.unlines+    [ "if [ -f cabal.project.local ]; then"+    , "  echo '::error::The repository contains cabal.project.local, which holds the settings of one developer. Move the settings to cabal.project or to the key cabal-project-local of the configuration of haskell-gha, and remove the file from the repository.'"+    , "  exit 1"+    , "fi"+    ]+    <> heredoc settings+  where+    settings :: [T.Text]+    settings =+      concat+        [ ["jobs: " <> tshow config.cabalJobs.value]+        , ["tests: True" | config.tests]+        , ["benchmarks: True" | config.benchmarks]+        , ["write-ghc-environment-files: always" | doctest]+        , concat+            [ "" : programOptions config.ghcOptions.value+            | not (T.null config.ghcOptions.value)+            ]+        , case T.lines (T.dropWhileEnd isSpace config.cabalProjectLocal.value) of+            [] -> []+            ls -> "" : ls+        ]++-- | Make GHC compile the modules of the local packages in parallel.+parallelScript+  :: Int+  -- ^ The number of parallel jobs.+  -> T.Text+parallelScript jobs = heredoc (programOptions ("-j" <> tshow jobs))++-- | Enable the GHC job semaphore, or parallel module builds if GHC and cabal+-- use different versions of the semaphore protocol. With different versions,+-- GHC compiles the modules one at a time. Only some minor versions of a series+-- use version 2, and a series entry gets its newest release when the job runs,+-- so the script asks GHC. A GHC without the Semaphore version entry in its info+-- uses version 1.+semaphoreScript+  :: Int+  -- ^ The number of parallel jobs.+  -> CabalVersion+  -> T.Text+semaphoreScript jobs (CabalVersion cabal) =+  T.concat+    [ "if ghc --info | grep -F '(\"Semaphore version\",\"2\")' > /dev/null; then\n"+    , branch 2+    , "else\n"+    , branch 1+    , "fi\n"+    ]+  where+    branch :: Int -> T.Text+    branch ghcV+      | ghcV == cabalV =+          echo+            ( "GHC and cabal use version "+                <> tshow ghcV+                <> " of the semaphore protocol, so GHC uses the semaphore."+            )+            <> heredoc ["semaphore: True"]+      | otherwise =+          echo+            ( "GHC uses version "+                <> tshow ghcV+                <> " of the semaphore protocol and cabal version "+                <> tshow cabalV+                <> ", so GHC uses -j"+                <> tshow jobs+                <> "."+            )+            <> parallelScript jobs++    echo :: T.Text -> T.Text+    echo msg = "echo '" <> msg <> "'\n"++    -- cabal 3.18 and later use only version 2, older versions only version 1.+    cabalV :: Int+    cabalV+      | cabal >= mkVersion [3, 18] = 2+      | otherwise = 1++-- | Run cabal check for each package. cabal check works on the package in the+-- current directory, and its output does not name the package. The step runs+-- with bash -e, so a failed check must not end the script before the other+-- packages.+checkScript :: [Package] -> T.Text+checkScript pkgs =+  T.unlines $+    concat+      [+        [ "failed=0"+        , "check() {"+        , "  echo \"Checking the package $1\""+        , "  (cd \"$2\" && cabal check) || { echo \"::error::cabal check failed for the package $1\"; failed=1; }"+        , "}"+        ]+      , [ "check " <> shellQuote (T.pack p.name) <> " " <> shellQuote (T.pack p.directory)+        | p <- pkgs+        ]+      , ["exit \"$failed\""]+      ]++-- | Run doctest for the library and each sublibrary of a package.+doctestScript+  :: [T.Text]+  -- ^ Extra arguments for doctest.+  -> Package+  -> T.Text+doctestScript options p =+  T.unlines $+    ["cd " <> shellQuote (T.pack p.directory) | p.directory /= "."]+      ++ [ T.unwords ("\"$HOME\"/.local/bin/doctest" : map shellQuote (options ++ map T.pack args))+         | args <- p.doctestArgs+         ]++----------------------------------------+-- Helpers++-- | GHC options for the local packages. cabal applies the program-options+-- stanza only to them, not to a package from Hackage or from a+-- source-repository-package. cabal merges several such stanzas, and the+-- ghc-options of a package stanza come after them.+programOptions :: T.Text -> [T.Text]+programOptions options = ["program-options", "  ghc-options: " <> options]++-- | Add lines to @cabal.project.local@.+heredoc :: [T.Text] -> T.Text+heredoc ls = T.unlines $ ["cat >> cabal.project.local <<'EOF'"] ++ ls ++ ["EOF"]++tshow :: Int -> T.Text+tshow = T.pack . show
+ src/HaskellGha/Workflow/Validate.hs view
@@ -0,0 +1,181 @@+-- | The checks of the configuration against the project, before the tool+-- generates the workflow.+module HaskellGha.Workflow.Validate+  ( -- * Validation+    validateWorkflow+  ) where++import Control.Monad+import Data.Foldable+import Data.List qualified as L+import Data.Text qualified as T+import Distribution.Pretty+import Distribution.Version+import System.FilePath+import Yamlet++import HaskellGha.Check+import HaskellGha.Command.Options+import HaskellGha.Config+import HaskellGha.Path+import HaskellGha.Project+import HaskellGha.Project.Ghc+import HaskellGha.Yaml++-- | Check that the workflow can be generated from the configuration and the+-- project.+validateWorkflow+  :: Options+  -> ConfigSource+  -> Config+  -> Project+  -> [T.Text]+  -- ^ The ids of the steps that the tool makes in the build job.+  -> Check ()+validateWorkflow opts source config project stepIds = do+  traverse_ checkGhcValue (combinationValues "ghc" combinations)+  checkDependencies+  for_ config.doctest.value $ \d -> do+    checkRange d.ghc+    traverse_ checkSkip d.skipPackages+  traverse_ checkImport project.imports+  when (config.buildFrom == BuildFromTarballs) $+    traverse_ checkInside project.packages+  traverse_ checkHLintPath (foldMap (.paths) config.hlint.value)+  traverse_ checkHookId (config.hooks.afterSetup ++ config.hooks.afterBuild)+  where+    entries :: [GhcEntry]+    entries = map (.ghc) project.matrix++    axisText :: String+    axisText = L.intercalate ", " (map (T.unpack . entryText) entries)++    combinations :: [[(T.Text, Located T.Text)]]+    combinations = config.matrix.value.include ++ config.matrix.value.exclude++    -- An error at a value of the configuration, with its position.+    failureAt :: Offset -> String -> Check ()+    failureAt off msg = traverse_ failure (sourceErrors source [(off, msg)])++    -- The action gets the path on the runner, where only the repository exists.+    checkHLintPath :: Located HLintPath -> Check ()+    checkHLintPath p+      | leadsOut (opts.projectDir </> path) =+          failureAt p.offset $+            "the path "+              ++ path+              ++ " is not in the repository. Give a path relative to the project directory."+      | otherwise = pure ()+      where+        path :: FilePath+        path = T.unpack p.value.value++    -- GitHub rejects a workflow if two steps of a job have the same id. It+    -- compares the ids without case (the StringComparer.OrdinalIgnoreCase of+    -- IdBuilder.cs in actions/runner), and an id has only ASCII characters.+    checkHookId :: MappingNode -> Check ()+    checkHookId s = case stringField "id" s.value of+      Just i+        | Just own <- L.find (\t -> T.toLower t == T.toLower i.value) stepIds ->+            failureAt i.offset $+              "the build job already has a step with the id "+                ++ T.unpack own+                ++ (if own == i.value then "" else ", and GitHub compares the ids without case")+                ++ ". Give the hook step another id."+      _ -> pure ()++    -- cabal fetches an import from a URL. It reads a local file on the runner,+    -- where only the repository exists, and the copy of the source tarballs+    -- does not contain it.+    checkImport :: Import -> Check ()+    checkImport i+      | isUrl i.target = pure ()+      | leadsOut (opts.projectDir </> i.target) =+          failure $+            i.location+              ++ "the imported file "+              ++ i.target+              ++ " is not in the repository. Give a path relative to the project directory."+      | config.buildFrom == BuildFromTarballs =+          failure $+            i.location+              ++ "the workflow builds the source tarballs in a copy of the project directory, and the copy does not contain the imported file "+              ++ i.target+              ++ ". Set build-from: checkout in the configuration."+      | otherwise = pure ()++    -- The unpack step keeps the path of each package relative to the project+    -- directory, so a path with .. leads out of the copy.+    checkInside :: Package -> Check ()+    checkInside p+      | leadsAbove p.directory =+          failure $+            "Package "+              ++ p.name+              ++ " is in "+              ++ p.directory+              ++ ", outside the project directory, but the workflow builds the source tarballs in a copy of the project directory. Set build-from: checkout in the configuration."+      | otherwise = pure ()++    -- A range that includes no matrix entry turns its feature off without any+    -- sign in the workflow, e.g. ==10.0 for the series 10.0.+    checkRange :: Located VersionRange -> Check ()+    checkRange r = do+      traverse_+        (either (failureAt r.offset) (const (pure ())) . decideRange name r.value)+        entries+      when (all (\e -> decide r.value e == Excluded) entries)+        $ failureAt r.offset+        $ name+          ++ " includes no GHC version of the matrix, which contains only "+          ++ axisText+      where+        name :: String+        name = "the range " ++ prettyShow r.value++    checkSkip :: Located T.Text -> Check ()+    checkSkip p+      | T.unpack p.value `elem` map (.name) project.packages = pure ()+      | otherwise = failureAt p.offset $ "the project has no local package " ++ T.unpack p.value++    -- The tool makes the dependencies axis only for both. Otherwise the name is+    -- free for an axis of the user.+    checkDependencies :: Check ()+    checkDependencies+      | config.dependencies == DependenciesBoth = do+          traverse_ ownAxis [a.offset | a <- config.matrix.value.axes, a.value == "dependencies"]+          traverse_ value (combinationValues "dependencies" combinations)+      | "dependencies" `elem` map (.value) config.matrix.value.axes = pure ()+      | otherwise =+          traverse_ noAxis (combinationValues "dependencies" config.matrix.value.exclude)+      where+        ownAxis :: Offset -> Check ()+        ownAxis off =+          failureAt+            off+            "the tool makes the dependencies axis for dependencies: both, so the matrix must not contain it"++        value :: Located T.Text -> Check ()+        value v+          | v.value `elem` ["newest", "oldest"] = pure ()+          | otherwise =+              failureAt v.offset $+                "dependencies "+                  ++ T.unpack v.value+                  ++ " is not in the dependencies axis, which contains only newest, oldest"++        noAxis :: Located T.Text -> Check ()+        noAxis v =+          failureAt+            v.offset+            "the matrix has no dependencies axis. Set dependencies: both to add it."++    checkGhcValue :: Located T.Text -> Check ()+    checkGhcValue v+      | v.value `elem` map entryText entries = pure ()+      | otherwise =+          failureAt v.offset $+            "GHC "+              ++ T.unpack v.value+              ++ " is not in the ghc axis, which contains only "+              ++ axisText
+ src/HaskellGha/Yaml.hs view
@@ -0,0 +1,111 @@+-- | Helpers to build and render the YAML tree of yamlet.+module HaskellGha.Yaml+  ( -- * Construction+    plain+  , nullValue+  , singleQuoted+  , literal+  , addBefore+  , mapBefore++    -- * Inspection+  , stringField++    -- * Rendering+  , renderDocument+  ) where++import Data.Maybe+import Data.Text qualified as T+import Yamlet+import Yamlet.Schema+import Yamlet.Syntax++----------------------------------------+-- Construction++-- | A string as a plain scalar, or as a single-quoted scalar if the plain+-- scalar does not read back as the same string.+plain :: T.Text -> Node+plain t = scalarNode (if isPlainSafe t then Plain else SingleQuoted) t++-- | The null value, as an empty plain scalar.+nullValue :: Node+nullValue = plainNode ""++-- | A single-quoted scalar.+singleQuoted :: T.Text -> Node+singleQuoted = scalarNode SingleQuoted++-- | A literal block scalar.+literal :: T.Text -> Node+literal = scalarNode Literal++-- | Put lines above a node, in front of the lines that it already has.+addBefore :: [Line] -> Node -> Node+addBefore ls = mapBefore (ls ++)++-- | Change the lines above a node.+mapBefore :: ([Line] -> [Line]) -> Node -> Node+mapBefore f n = withComments n.comments {before = f n.comments.before} n++----------------------------------------+-- Inspection++-- | The scalar value of a key of a mapping, with its position.+stringField :: T.Text -> Node -> Maybe (Located T.Text)+stringField key n = case n.content of+  MappingContent _ entries ->+    listToMaybe+      [ Located t v.offset+      | (Node {content = ScalarContent _ k}, v@Node {content = ScalarContent _ t}) <- entries+      , k == key+      ]+  _ -> Nothing++----------------------------------------+-- Rendering++-- | Render a node as a YAML document in the block style.+renderDocument+  :: [T.Text]+  -- ^ The header lines. They become comments at the start of the document, with+  -- an empty line below them.+  -> ([T.Text] -> Bool)+  -- ^ The collections with an empty line between their entries, by the keys on+  -- the path to them.+  -> Node+  -> T.Text+renderDocument header separated root =+  renderSyntax+    defaultRenderOptions {forceBlock = True}+    -- The header goes on the root node, because on the document it would+    -- need a --- marker below it.+    [ Document+        { version = Nothing+        , explicitStart = False+        , explicitEnd = False+        , docComments = noComments+        , root = addBefore (map Comment header) (separate [] root)+        }+    ]+  where+    separate :: [T.Text] -> Node -> Node+    separate path n = case n.content of+      MappingContent style entries -> n {content = MappingContent style (zipWith entry [0 ..] entries)}+      SequenceContent style items+        | separated path -> n {content = SequenceContent style (zipWith spaced [0 ..] items)}+      _ -> n+      where+        entry :: Int -> (Node, Node) -> (Node, Node)+        entry i (k, v) =+          ( spaced i k+          , case k.content of+              ScalarContent _ name -> separate (path ++ [name]) v+              _ -> v+          )++        spaced :: Int -> Node -> Node+        spaced i x+          | i > 0 && separated path = addBefore [EmptyLine] x+          | otherwise = x
+ tests/HaskellGha/Test/Config.hs view
@@ -0,0 +1,605 @@+module HaskellGha.Test.Config (configTests) where++import Control.Monad+import Data.ByteString qualified as BS+import Data.List.NonEmpty qualified as NE+import Data.Maybe+import Data.Text qualified as T+import Data.Text.Encoding qualified as T+import Distribution.Version+import System.Directory+import System.FilePath+import System.IO.Temp+import Test.Tasty+import Test.Tasty.HUnit+import Yamlet+import Yamlet.Syntax++import HaskellGha.Config+import HaskellGha.Test.Helpers+import HaskellGha.Yaml++configTests :: TestTree+configTests =+  testGroup+    "Config"+    [ testCase "a missing file" test_missingFile+    , testCase "a broken file" test_brokenFile+    , testCase "an empty file gives the defaults" test_emptyFile+    , testCase "the example configuration" test_example+    , testCase "the example configuration of the README" test_readmeExample+    , testCase "recursive submodules" test_recursiveSubmodules+    , testCase "a folded ghc-options value" test_foldedGhcOptions+    , testCase "errors" test_errors+    , testCase "all errors are collected" test_allErrors+    , testCase "errors give the line and the column" test_locations+    , testCase "an alias in a hook" test_alias+    ]++test_missingFile :: Assertion+test_missingFile = do+  -- The directory has no default configuration file.+  optional <- readConfig "tests" DefaultConfigFile+  assertEqual "default" (Right defaultConfig) (fst <$> optional)+  required <- readConfig "." (ConfigFile "tests/does-not-exist.yml")+  assertEqual+    "named"+    (Left ["The configuration file tests/does-not-exist.yml does not exist."])+    (fst <$> required)++test_brokenFile :: Assertion+test_brokenFile =+  withSystemTempDirectory "haskell-gha-tests" $ \root -> do+    let file = root </> defaultConfigPath+        broken =+          Left+            [ "The configuration file "+                ++ defaultConfigPath+                ++ " is a directory or a broken symbolic link."+            ]+    createDirectoryIfMissing True (takeDirectory file)+    createFileLink (root </> "missing.yml") file+    assertEqual "broken link" broken . fmap fst =<< readConfig root DefaultConfigFile+    removeFile file+    createDirectory file+    assertEqual "directory" broken . fmap fst =<< readConfig root DefaultConfigFile+    forM_ [".", defaultConfigPath ++ "/"] $ \path ->+      assertEqual+        ("directory " ++ path)+        (Left ["The configuration file " ++ path ++ " is a directory or a broken symbolic link."])+        . fmap fst+        =<< readConfig root (ConfigFile path)++test_emptyFile :: Assertion+test_emptyFile = assertEqual "config" (Right defaultConfig) (parse "# only a comment\n")++test_example :: Assertion+test_example = do+  config <-+    parseOk $+      T.unlines+        [ "name: Tests"+        , "cabal-version: 3.14.2.0"+        , "runs-on: ubuntu-24.04"+        , "container: buildpack-deps:22.04"+        , "timeout-minutes: 30"+        , "branches: [master]"+        , "submodules: true"+        , "matrix:"+        , "  postgres: ['15', '18']"+        , "  exclude:"+        , "    - ghc: '9.10'"+        , "      postgres: '15'"+        , "apt: [libpq-dev]"+        , "services:"+        , "  postgres:"+        , "    image: postgres:${{ matrix.postgres }}"+        , "permissions: read-all"+        , "hooks:"+        , "  after-setup:"+        , "    - name: Show the Postgres version"+        , "      run: psql --version"+        , "  after-build: []"+        , "ghc-options: -Werror -Wno-unused"+        , "cabal-project-local: |"+        , "  package a"+        , "    flags: +b"+        , "cabal-jobs: 2"+        , "tests: false"+        , "benchmarks: False"+        , "dependencies: both"+        , "doctest:"+        , "  ghc: '>=9.6 && <9.14'"+        , "  version: '>=0.24'"+        , "  skip-packages: [some-package]"+        , "  options: [--fast]"+        , "cabal-check: false"+        , "build-from: checkout"+        , "haddock: false"+        , "fourmolu:"+        , "  version: 0.19.0.1"+        , "  patterns: ['src/**/*.hs']"+        , "hlint:"+        , "  version: '3.10'"+        , "  fail-on: error"+        , "  paths: [src]"+        , "actions:"+        , "  checkout: v8"+        , "  cache: runs-on/cache@v4"+        , "  run-fourmolu: v12"+        , "  hlint-setup: 0123abc"+        , "  hlint-run: v2"+        ]+  assertEqual "name" "Tests" config.name.value+  assertEqual "cabal-version" (CabalVersion $ mkVersion [3, 14, 2, 0]) config.cabalVersion+  assertEqual "runs-on" (plain "ubuntu-24.04") (normalize config.runsOn.value.value)+  assertEqual "container" (Just (Container "buildpack-deps:22.04")) config.container.value+  assertEqual "timeout-minutes" 30 config.timeoutMinutes.value+  assertEqual "branches" ["master"] (map (.value) (NE.toList config.branches.value))+  assertEqual "submodules" TopSubmodules config.submodules+  assertEqual "matrix axes" ["postgres"] (map (.value) config.matrix.value.axes)+  assertEqual+    "matrix ghc values"+    ["9.10"]+    ( map+        (.value)+        (combinationValues "ghc" (config.matrix.value.include ++ config.matrix.value.exclude))+    )+  assertEqual "apt" ["libpq-dev"] config.apt+  assertBool "services" (isJust config.services.value)+  assertEqual "permissions" (plain "read-all") (normalize config.permissions.value.value)+  assertEqual "after-setup" 1 (length config.hooks.afterSetup)+  assertEqual "after-build" 0 (length config.hooks.afterBuild)+  assertEqual "ghc-options" "-Werror -Wno-unused" config.ghcOptions.value+  assertEqual+    "cabal-project-local"+    "package a\n  flags: +b\n"+    config.cabalProjectLocal.value+  assertEqual "cabal-jobs" 2 config.cabalJobs.value+  assertEqual "tests" False config.tests+  assertEqual "benchmarks" False config.benchmarks+  assertEqual "dependencies" DependenciesBoth config.dependencies+  doctest <- maybe (assertFailure "no doctest") pure config.doctest.value+  assertEqual+    "doctest ghc"+    ( intersectVersionRanges+        (orLaterVersion $ mkVersion [9, 6])+        (earlierVersion $ mkVersion [9, 14])+    )+    doctest.ghc.value+  assertEqual+    "doctest version"+    (Just (orLaterVersion $ mkVersion [0, 24]))+    doctest.version.value+  assertEqual "doctest skip-packages" ["some-package"] (map (.value) doctest.skipPackages)+  assertEqual "doctest options" ["--fast"] doctest.options+  assertEqual "cabal-check" False config.cabalCheck+  assertEqual "build-from" BuildFromCheckout config.buildFrom+  assertEqual "haddock" False config.haddock+  assertEqual+    "fourmolu"+    ( Just+        Fourmolu+          { version = mkVersion [0, 19, 0, 1]+          , patterns = [Pattern "src/**/*.hs"]+          , runsOn = Optional Nothing+          }+    )+    config.fourmolu.value+  hlint <- maybe (assertFailure "no hlint") pure config.hlint.value+  assertEqual "hlint version" (mkVersion [3, 10]) hlint.version+  assertEqual "hlint fail-on" FailError hlint.failOn+  assertEqual "hlint path" [HLintPath "src"] (map (.value) hlint.paths)+  assertEqual+    "actions"+    ( Actions+        { checkout = ActionRef {repository = Nothing, ref = "v8"}+        , cache = ActionRef {repository = Just "runs-on/cache", ref = "v4"}+        , runFourmolu = ActionRef {repository = Nothing, ref = "v12"}+        , hlintSetup = ActionRef {repository = Nothing, ref = "0123abc"}+        , hlintRun = ActionRef {repository = Nothing, ref = "v2"}+        }+    )+    config.actions++-- The golden test readme generates a workflow from the example configuration of+-- the README, so the example stays valid.+test_readmeExample :: Assertion+test_readmeExample = do+  readme <- T.decodeUtf8 <$> BS.readFile "README.md"+  config <-+    T.decodeUtf8+      <$> BS.readFile ("tests" </> "golden" </> "readme" </> "haskell-gha.conf.yaml")+  assertBool+    "README.md shows tests/golden/readme/haskell-gha.conf.yaml"+    (("```yaml\n" <> config <> "```\n") `T.isInfixOf` readme)++test_recursiveSubmodules :: Assertion+test_recursiveSubmodules = do+  config <- parseOk "submodules: recursive\n"+  assertEqual "submodules" RecursiveSubmodules config.submodules++test_foldedGhcOptions :: Assertion+test_foldedGhcOptions = do+  config <- parseOk "ghc-options: >\n  -Wall\n  -Werror\n"+  assertEqual "ghc-options" "-Wall -Werror" config.ghcOptions.value++test_errors :: Assertion+test_errors = do+  assertError+    "not a mapping"+    "expected a mapping, but got a list"+    "- a\n"+  assertError+    "unknown key"+    "unknown key \"cabal-job\", did you mean \"cabal-jobs\"?"+    "cabal-job: 4\n"+  assertError+    "unknown hooks key"+    "hooks: unknown key \"before-build\", expected one of: after-setup, after-build"+    "hooks:\n  before-build: []\n"+  assertError+    "unknown doctest key"+    "doctest: unknown key \"flags\", expected one of: ghc, version, skip-packages, options"+    "doctest:\n  flags: []\n"+  assertError+    "two documents"+    "expected a single document, but got a second one"+    "cabal-jobs: 1\n---\ncabal-jobs: 2\n"+  assertError+    "cabal-jobs"+    "cabal-jobs: expected a positive integer"+    "cabal-jobs: 0\n"+  assertError+    "cabal-jobs type"+    "cabal-jobs: expected a positive integer"+    "cabal-jobs: four\n"+  assertError+    "cabal-jobs null"+    "cabal-jobs: expected a positive integer"+    "cabal-jobs: ~\n"+  assertError+    "timeout-minutes"+    "timeout-minutes: expected a positive integer"+    "timeout-minutes: 0\n"+  assertError+    "tests"+    "tests: expected a boolean, but got a string"+    "tests: 'true'\n"+  assertError+    "branches"+    "branches: expected a non-empty list"+    "branches: []\n"+  assertError+    "container"+    (containerError "ubuntu:26.04")+    "container: ubuntu:26.04\n"+  assertError+    "container codename"+    (containerError "buildpack-deps:resolute")+    "container: buildpack-deps:resolute\n"+  assertError+    "container interim release"+    "container: unknown value \"buildpack-deps:26.10\", did you mean \"buildpack-deps:26.04\"?"+    "container: buildpack-deps:26.10\n"+  assertError+    "dependencies"+    "dependencies: unknown value \"old\", expected one of: newest, oldest, both"+    "dependencies: old\n"+  assertError+    "build-from"+    "build-from: expected one of: tarballs, checkout, but got a boolean"+    "build-from: false\n"+  assertError+    "submodules"+    "submodules: expected true, false or recursive"+    "submodules: 'yes'\n"+  assertError+    "runs-on"+    "runs-on: expected a runner label, a list of labels or a mapping"+    "runs-on: 1\n"+  assertError+    "runs-on label"+    "runs-on[1]: expected a string, but got an integer, quote the value, e.g. '1'"+    "runs-on: [self-hosted, 1]\n"+  assertError+    "unquoted number"+    "hlint.version: expected a string, but got a floating-point number, quote the value, e.g. '3.10'"+    "hlint:\n  version: 3.10\n"+  assertError+    "unquoted boolean"+    "apt[0]: expected a string, but got a boolean, quote the value, e.g. 'true'"+    "apt: [true]\n"+  assertError+    "old cabal"+    "cabal-version: the tool supports only cabal 3.12 and later"+    "cabal-version: 3.10.3.0\n"+  assertError+    "cabal latest"+    cabalError+    "cabal-version: latest\n"+  assertError+    "cabal series"+    cabalError+    "cabal-version: '3.16'\n"+  assertError+    "cabal version with three parts"+    cabalError+    "cabal-version: 3.16.1\n"+  assertError+    "ghc axis"+    "matrix: the tool makes the ghc axis, so the matrix must not contain it"+    "matrix:\n  ghc: ['9.10']\n"+  assertError+    "axis name"+    "matrix: the axis name \"os x\" is not valid in a GitHub expression. A name must start with a letter or _, and contain only letters, digits, _ and -, e.g. os-version"+    "matrix:\n  os x: ['a']\n"+  assertError+    "axis name start"+    "matrix: the axis name \"1os\" is not valid in a GitHub expression. A name must start with a letter or _, and contain only letters, digits, _ and -, e.g. os-version"+    "matrix:\n  1os: ['a']\n"+  assertError+    "unquoted ghc"+    "matrix.include[0].ghc: a ghc value must be a quoted string, e.g. '9.10'"+    "matrix:\n  include:\n    - ghc: 9.10\n"+  assertError+    "exclude"+    "matrix.exclude: expected a list of mappings, but got a string"+    "matrix:\n  exclude: '9.10'\n"+  assertError+    "include item"+    "matrix.include[0]: expected a mapping, but got a string"+    "matrix:\n  include:\n    - '9.10'\n"+  assertError+    "exclude key"+    "matrix.exclude[0]: version is not an axis of the matrix. The axes are: ghc, postgres"+    "matrix:\n  postgres: ['15', '18']\n  exclude:\n    - ghc: '9.10'\n      version: '15'\n"+  assertError+    "services"+    "services: expected a mapping, but got a list"+    "services: [postgres]\n"+  assertError+    "permissions"+    "permissions: expected a mapping, read-all or write-all"+    "permissions: [contents]\n"+  assertError+    "permissions scalar"+    "permissions: expected a mapping, read-all or write-all"+    "permissions: read\n"+  assertError+    "hooks null"+    "hooks: expected a mapping, but got null"+    "hooks:\n"+  assertError+    "step"+    "hooks.after-setup[0]: expected a mapping, but got a string"+    "hooks:\n  after-setup:\n    - make\n"+  assertError+    "container null"+    "container: expected one of: buildpack-deps:22.04, buildpack-deps:24.04, buildpack-deps:26.04, but got null"+    "container:\n"+  assertError+    "services null"+    "services: expected a mapping, but got null"+    "services: null\n"+  assertError+    "doctest null"+    "doctest: expected a mapping, but got null"+    "doctest:\n"+  assertError+    "doctest range"+    "doctest.ghc: expected a version range, e.g. '>=1.2' or '==1.2.3'"+    "doctest:\n  ghc: nine\n"+  assertError+    "doctest bare version"+    "doctest.version: expected a version range, e.g. '>=1.2' or '==1.2.3'"+    "doctest:\n  version: 0.24.2\n"+  assertError+    "doctest version null"+    "doctest.version: expected a string, but got null"+    "doctest:\n  version:\n"+  assertError+    "hlint runs-on null"+    "hlint.runs-on: expected a runner label, a list of labels or a mapping"+    "hlint:\n  version: '3.10'\n  runs-on:\n"+  assertError+    "fourmolu runs-on null"+    "fourmolu.runs-on: expected a runner label, a list of labels or a mapping"+    "fourmolu:\n  version: 0.21.0.0\n  runs-on: ~\n"+  assertError+    "apt"+    "apt: expected a list, but got a string"+    "apt: libpq-dev\n"+  assertError+    "cabal-project-local"+    "cabal-project-local: a line must not be EOF"+    "cabal-project-local: |\n  tests: True\n  EOF\n"+  assertError+    "unknown action"+    "actions: unknown key \"run-ormolu\", did you mean \"run-fourmolu\"?"+    "actions:\n  run-ormolu: v17\n"+  assertError+    "hlint without version"+    "hlint: missing key \"version\""+    "hlint:\n  fail-on: error\n"+  assertError+    "fourmolu without version"+    "fourmolu: missing key \"version\""+    "fourmolu:\n  patterns: ['src/**/*.hs']\n"+  assertError+    "fourmolu version"+    "fourmolu.version: expected a version, e.g. 0.21.0.0"+    "fourmolu:\n  version: latest\n"+  assertError+    "hlint path"+    "hlint.paths[1]: a path must not contain a control character, e.g. a tab or a line break"+    "hlint:\n  version: '3.10'\n  paths: [src, \"a\\tb\"]\n"+  assertError+    "empty hlint path"+    "hlint.paths[1]: a path must not be empty"+    "hlint:\n  version: '3.10'\n  paths: [src, \"\"]\n"+  assertError+    "hlint fail-on"+    "hlint.fail-on: unknown value \"warnings\", did you mean \"warning\"?"+    "hlint:\n  version: '3.10'\n  fail-on: warnings\n"+  assertError+    "unknown fourmolu key"+    "fourmolu: unknown key \"extra-args\", expected one of: version, patterns, runs-on"+    "fourmolu:\n  version: 0.21.0.0\n  extra-args: [-q]\n"+  assertError+    "action ref"+    actionError+    "actions:\n  checkout: 'v 2'\n"+  assertError+    "action without owner"+    actionError+    "actions:\n  checkout: checkout@v2\n"+  assertError+    "action with a path"+    actionError+    "actions:\n  checkout: a/b/c@v2\n"+  assertError+    "action without ref"+    actionError+    "actions:\n  checkout: a/b@\n"+  assertError+    "action with two refs"+    actionError+    "actions:\n  checkout: a/b@v1@v2\n"+  assertError+    "ghc-options lines"+    "ghc-options: the value must be one line"+    "ghc-options: |\n  -Wall\n  -Werror\n"+  assertError+    "fourmolu pattern space"+    "fourmolu.patterns[0]: a pattern must be one line without spaces at the start or the end"+    "fourmolu:\n  version: 0.21.0.0\n  patterns: [' src/**/*.hs']\n"+  assertError+    "fourmolu pattern lines"+    "fourmolu.patterns[0]: a pattern must be one line without spaces at the start or the end"+    "fourmolu:\n  version: 0.21.0.0\n  patterns: [\"a.hs\\nb.hs\"]\n"+  assertError+    "cabal-project-local type"+    "cabal-project-local: expected a string, but got a list"+    "cabal-project-local: [tests]\n"+  where+    assertError :: String -> String -> T.Text -> Assertion+    assertError preface expected input =+      assertEqual+        preface+        (Left [expected])+        (either (Left . map dropLocation) Right . firstLines $ parse input)++    -- The file name has no space, so the location ends at the first space.+    dropLocation :: String -> String+    dropLocation = drop 1 . dropWhile (/= ' ')++    containerError :: String -> String+    containerError image =+      "container: unknown value "+        ++ show image+        ++ ", expected one of: buildpack-deps:22.04, buildpack-deps:24.04, buildpack-deps:26.04"++    cabalError :: String+    cabalError =+      "cabal-version: expected a release with four parts, e.g. 3.16.1.0"++    actionError :: String+    actionError =+      "actions.checkout: expected a Git ref, e.g. v7, or a repository with a Git ref, e.g. runs-on/cache@v4"++test_locations :: Assertion+test_locations = do+  assertEqual+    "excerpt"+    ( Left+        [ "conf.yml:2:12: hlint.version: expected a string, but got a floating-point number, quote the value, e.g. '3.10'\n  |\n2 |   version: 3.10\n  |            ^"+        ]+    )+    (parse "hlint:\n  version: 3.10\n")+  assertEqual+    "root"+    (Left ["conf.yml:1:1: expected a mapping, but got a list"])+    (firstLines $ parse "- a\n")+  assertEqual+    "nested key"+    ( Left+        [ "conf.yml:2:3: hooks: unknown key \"before-build\", expected one of: after-setup, after-build"+        ]+    )+    (firstLines $ parse "hooks:\n  before-build: []\n")+  assertEqual+    "duplicate key"+    ( Left+        [ "conf.yml:2:1: duplicate key \"cabal-jobs\""+        , "conf.yml:1:1: the first key \"cabal-jobs\""+        ]+    )+    (firstLines $ parse "cabal-jobs: 1\ncabal-jobs: 2\n")+  assertEqual+    "list item"+    ( Left+        [ "conf.yml:1:13: apt[2]: expected a string, but got a boolean, quote the value, e.g. 'true'"+        ]+    )+    (firstLines $ parse "apt: [a, b, true]\n")+  assertEqual+    "matrix key"+    ( Left+        [ "conf.yml:4:7: matrix.exclude[0]: version is not an axis of the matrix. The axes are: ghc, postgres"+        ]+    )+    (firstLines $ parse "matrix:\n  postgres: ['15']\n  exclude:\n    - version: '15'\n")++test_allErrors :: Assertion+test_allErrors = do+  assertEqual+    "fields"+    ( Left+        [ "conf.yml:1:1: unknown key \"cabal-job\", did you mean \"cabal-jobs\"?"+        , "conf.yml:2:8: tests: expected a boolean, but got an integer"+        , "conf.yml:3:13: cabal-jobs: expected a positive integer"+        ]+    )+    (firstLines $ parse "cabal-job: 1\ntests: 1\ncabal-jobs: -1\n")+  assertEqual+    "matrix"+    ( Left+        [ "conf.yml:2:3: matrix: the axis name \"os x\" is not valid in a GitHub expression. A name must start with a letter or _, and contain only letters, digits, _ and -, e.g. os-version"+        , "conf.yml:3:3: matrix: the tool makes the ghc axis, so the matrix must not contain it"+        , "conf.yml:5:12: matrix.include[0].ghc: a ghc value must be a quoted string, e.g. '9.10'"+        , "conf.yml:8:7: matrix.exclude[0]: version is not an axis of the matrix. The axes are: ghc, os x"+        ]+    )+    ( firstLines $+        parse+          "matrix:\n  os x: [a]\n  ghc: ['9.10']\n  include:\n    - ghc: 9.10\n  exclude:\n    - ghc: '9.10'\n      version: '15'\n"+    )++test_alias :: Assertion+test_alias = do+  config <-+    parseOk "hooks:\n  after-setup:\n    - &step {run: a}\n  after-build:\n    - *step\n"+  assertEqual+    "after-build"+    (contents config.hooks.afterSetup)+    (contents config.hooks.afterBuild)+  where+    -- The copy of an alias has no anchor.+    contents :: [MappingNode] -> [Content]+    contents = map (\s -> (normalize s.value).content)++----------------------------------------+-- Helpers++-- | The first line of each error, without the excerpt of the input.+firstLines :: Either [String] a -> Either [String] a+firstLines = either (Left . map (takeWhile (/= '\n'))) Right++parse :: T.Text -> Either [String] Config+parse = fmap fst . parseConfig "conf.yml" . T.encodeUtf8++parseOk :: T.Text -> IO Config+parseOk input = case parse input of+  Left errors -> assertFailure $ unlines errors+  Right config -> pure config
+ tests/HaskellGha/Test/Golden.hs view
@@ -0,0 +1,80 @@+module HaskellGha.Test.Golden (goldenTests) where++import Control.Monad+import Data.ByteString qualified as BS+import Data.List qualified as L+import Data.Text qualified as T+import Data.Text.Encoding qualified as T+import Options.Applicative+import System.Directory+import System.Environment+import System.Exit+import System.FilePath+import System.Process+import Test.Tasty+import Test.Tasty.HUnit+import Yamlet+import Yamlet.Syntax++import HaskellGha.Command+import HaskellGha.Command.Header+import HaskellGha.Command.Options+import HaskellGha.Test.Helpers++-- | A test for each directory in @tests/golden@. The test runs the tool in the+-- directory, with the arguments from the file @args@. If the directory contains+-- @haskell-gha.conf.yaml@, the test uses it as the configuration.+goldenTests :: IO TestTree+goldenTests = do+  fixtures <- L.sort <$> listDirectory goldenDir+  pure . testGroup "Golden" $ [testCase fixture (golden fixture) | fixture <- fixtures]+  where+    goldenDir :: FilePath+    goldenDir = "tests" </> "golden"++    golden :: FilePath -> Assertion+    golden fixture = do+      let dir = goldenDir </> fixture+      args <- readArgs (dir </> "args")+      hasConfig <- doesFileExist (dir </> "haskell-gha.conf.yaml")+      let args' =+            if hasConfig && "--config" `notElem` args+              then args ++ ["--config", "haskell-gha.conf.yaml"]+              else args+      opts <- case execParserPure defaultPrefs (optionsParser "TEST") ("--generate" : args') of+        Success (Generate opts) -> pure opts+        _ -> assertFailure $ "invalid arguments: " ++ unwords args'+      result <- generate dir opts+      node <- either (assertFailure . unlines) pure result+      let actual = renderWorkflow opts node+          expectedFile = dir </> "expected.yaml"+      accept <- (== Just "1") <$> lookupEnv "HASKELL_GHA_ACCEPT"+      when accept $ BS.writeFile expectedFile (T.encodeUtf8 actual)+      expected <- T.decodeUtf8 <$> BS.readFile expectedFile+      assertEqual "workflow" expected actual+      case decodeText @(Maybe Node) actual of+        Right (Just reparsed) -> assertEqual "reparsed workflow" (normalize node) (normalize reparsed)+        Right Nothing -> assertFailure "the workflow is empty"+        Left errors -> assertFailure $ foldMap ((++ "\n") . prettyError expectedFile) errors+      forM_ (runScripts node) $ \script -> do+        -- The unpack script turns on extglob, but bash -n does not run it.+        (code, _, err) <- readProcessWithExitCode "bash" ["-n", "-O", "extglob"] (T.unpack script)+        assertEqual ("bash -n:\n" ++ T.unpack script ++ "\n" ++ err) ExitSuccess code+      where+        runScripts :: Node -> [T.Text]+        runScripts n = case n.content of+          MappingContent _ kvs ->+            concat+              [ case (k.content, v.content) of+                  (ScalarContent _ "run", ScalarContent _ script) -> [script]+                  _ -> runScripts v+              | (k, v) <- kvs+              ]+          SequenceContent _ items -> concatMap runScripts items+          _ -> []++        readArgs :: FilePath -> IO [String]+        readArgs path =+          doesFileExist path >>= \case+            True -> words <$> readFile path+            False -> pure []
+ tests/HaskellGha/Test/Helpers.hs view
@@ -0,0 +1,20 @@+module HaskellGha.Test.Helpers (normalize) where++import Yamlet.Syntax++-- | Remove the positions and the comments, and give every collection the block+-- style, as the renderer writes it. A parsed node then compares equal to a+-- built one.+normalize :: Node -> Node+normalize n =+  Node+    { offset = noOffset+    , endOffset = noOffset+    , props = n.props+    , comments = noComments+    , content = case n.content of+        SequenceContent _ xs -> SequenceContent Block (map normalize xs)+        MappingContent _ kvs ->+          MappingContent Block [(normalize k, normalize v) | (k, v) <- kvs]+        c -> c+    }
+ tests/HaskellGha/Test/Project.hs view
@@ -0,0 +1,653 @@+module HaskellGha.Test.Project (projectTests) where++import Control.Monad+import Data.Either+import Data.List qualified as L+import Distribution.Version+import System.Directory+import System.FilePath+import System.IO.Temp+import Test.Tasty+import Test.Tasty.HUnit++import HaskellGha.Project+import HaskellGha.Project.Ghc++projectTests :: TestTree+projectTests =+  testGroup+    "Project"+    [ testCase "a single package without cabal.project" test_single+    , testCase "a conditional block" test_conditional+    , testCase "elif and else" test_elifElse+    , testCase "a conditional block inside another" test_nested+    , testCase "import lines" test_imports+    , testCase "globs" test_globs+    , testCase "optional packages" test_optional+    , testCase "exact and series entries" test_exactAndSeries+    , testCase "an exact entry next to a series entry" test_exactNextToSeries+    , testCase "a missing conditional block" test_missingBlock+    , testCase "a tested-with version that the project excludes" test_untestedVersion+    , testCase "the paths of a project in the root" test_rootProject+    , testCase "a condition that includes a part of a series" test_partialCondition+    , testCase "a condition on the first release of a series" test_firstRelease+    , testCase "a flag condition" test_flagCondition+    , testCase "all errors of cabal.project are collected" test_projectFileErrors+    , testCase "a condition that the other side decides" test_decidedCondition+    , testCase "a negated condition" test_not+    , testCase "os and arch conditions" test_osArch+    , testCase "tested-with errors" test_testedWithErrors+    , testCase "no packages for a matrix entry" test_emptyEntry+    , testCase "package location errors" test_locationErrors+    , testCase+        "doctest sources in the package directory and a subdirectory"+        test_doctestRootAndSubdirectory+    , testCase+        "doctest sources with a trailing separator"+        test_doctestTrailingSeparator+    , testCase "a missing project directory" test_missingDirectory+    , testCase "a cabal.project in a parent directory" test_parentProject+    ]++test_parentProject :: Assertion+test_parentProject =+  withSystemTempDirectory "haskell-gha-tests" $ \tmp -> do+    let root = tmp </> "repo"+        write :: FilePath -> String -> IO ()+        write path contents = do+          createDirectoryIfMissing True (takeDirectory (tmp </> path))+          writeFile (tmp </> path) contents+        parentError :: String -> FilePath -> String+        parentError dir file =+          "The project directory "+            ++ show dir+            ++ " has no cabal.project, so cabal uses "+            ++ file+            ++ " of a parent directory, but the tool reads only the packages of the project directory. Give the directory of "+            ++ file+            ++ " to --project-dir, or add a cabal.project to "+            ++ show dir+            ++ "."+    write "cabal.project" "packages: repo/a\n"+    write "repo/a/a.cabal" (cabal "a" "GHC ^>= 9.10" False)+    assertBool "a file above the root" . isRight =<< readProject root "a"+    write "repo/cabal.project" "packages: a\n"+    write "repo/sub/cabal.project" "packages: inner\n"+    write "repo/sub/inner/b.cabal" (cabal "b" "GHC ^>= 9.10" False)+    assertEqual "the root" (Left [parentError "a" "cabal.project"]) =<< readProject root "a"+    assertEqual+      "the nearest parent"+      (Left [parentError "sub/inner" "sub/cabal.project"])+      =<< readProject root "sub/inner"+    createDirectoryLink "sub/inner" (root </> "link")+    assertEqual+      "a symbolic link"+      (Left [parentError "link" "sub/cabal.project"])+      =<< readProject root "link"++test_missingDirectory :: Assertion+test_missingDirectory = do+  result <- readProject "." "tests/does-not-exist"+  assertEqual+    "errors"+    (Left ["The project directory \"tests/does-not-exist\" does not exist."])+    result++test_single :: Assertion+test_single = do+  project <-+    readOk [("example.cabal", cabal "example" "GHC == 9.6.7 || ^>= 9.10 || ^>= 9.12" True)]+  assertEqual "packages" ["example"] (map (.name) project.packages)+  assertEqual "directory" ["."] (map (.directory) project.packages)+  assertEqual "test suite" [True] (map (.hasTestSuite) project.packages)+  assertEqual+    "matrix"+    [(v [9, 6, 7], ["example"]), (s 9 10, ["example"]), (s 9 12, ["example"])]+    (matrixOf project)++test_conditional :: Assertion+test_conditional = do+  project <-+    readOk+      [ ("cabal.project", "packages: core\n\nif impl(ghc >= 9.8)\n  packages: new\n")+      , ("core/core.cabal", cabal "core" "GHC == 9.6.7 || ^>= 9.8 || ^>= 9.10" False)+      , ("new/new.cabal", cabal "new" "GHC ^>= 9.8 || ^>= 9.10" True)+      ]+  assertEqual "packages" ["core", "new"] (map (.name) project.packages)+  assertEqual+    "matrix"+    [ (v [9, 6, 7], ["core"])+    , (s 9 8, ["core", "new"])+    , (s 9 10, ["core", "new"])+    ]+    (matrixOf project)++test_elifElse :: Assertion+test_elifElse = do+  project <-+    readOk+      [+        ( "cabal.project"+        , "if impl(ghc >= 9.12)\n  packages: c\nelif impl(ghc >= 9.8)\n  packages: b\nelse\n  packages: a\n"+        )+      , ("a/a.cabal", cabal "a" "GHC == 9.6.7" False)+      , ("b/b.cabal", cabal "b" "GHC ^>= 9.10" False)+      , ("c/c.cabal", cabal "c" "GHC ^>= 9.12" False)+      ]+  assertEqual+    "matrix"+    [(v [9, 6, 7], ["a"]), (s 9 10, ["b"]), (s 9 12, ["c"])]+    (matrixOf project)++test_nested :: Assertion+test_nested = do+  project <-+    readOk+      [+        ( "cabal.project"+        , "if impl(ghc >= 9.10)\n  if impl(ghc >= 9.12)\n    packages: c\n  else\n    packages: b\nelse\n  packages: a\n"+        )+      , ("a/a.cabal", cabal "a" "GHC == 9.6.7" False)+      , ("b/b.cabal", cabal "b" "GHC ^>= 9.10" False)+      , ("c/c.cabal", cabal "c" "GHC ^>= 9.12" False)+      ]+  assertEqual+    "matrix"+    [(v [9, 6, 7], ["a"]), (s 9 10, ["b"]), (s 9 12, ["c"])]+    (matrixOf project)++test_imports :: Assertion+test_imports = do+  project <-+    readOk+      [+        ( "cabal.project"+        , "packages: a\nimport: base.project\n\nif impl(ghc >= 9.12)\n  import: new.project\n"+        )+      , ("a/a.cabal", cabal "a" "GHC ^>= 9.10" False)+      ]+  assertEqual+    "imports"+    [ Import {location = "PROJECT/cabal.project:2:1: ", target = "base.project"}+    , Import {location = "PROJECT/cabal.project:5:3: ", target = "new.project"}+    ]+    project.imports++test_globs :: Assertion+test_globs = do+  project <-+    readOk+      [ ("cabal.project", "packages: pkgs/*/\n          other/*.cabal, {x,y}\n")+      , ("pkgs/a/a.cabal", cabal "a" "GHC ^>= 9.10" False)+      , ("pkgs/a/.#a.cabal", "")+      , ("pkgs/b/b.cabal", cabal "b" "GHC ^>= 9.10" False)+      , ("pkgs/docs/index.md", "")+      , ("pkgs/two/c.cabal", cabal "c" "GHC ^>= 9.10" False)+      , ("pkgs/two/d.cabal", cabal "d" "GHC ^>= 9.10" False)+      , ("other/o.cabal", cabal "o" "GHC ^>= 9.10" False)+      , ("x/x.cabal", cabal "x" "GHC ^>= 9.10" False)+      , ("y/y.cabal", cabal "y" "GHC ^>= 9.10" False)+      ]+  assertEqual "packages" ["a", "b", "o", "x", "y"] (L.sort $ map (.name) project.packages)+  assertEqual+    "directories"+    ["other", "pkgs/a", "pkgs/b", "x", "y"]+    (L.sort $ map (.directory) project.packages)+  twoPaths <-+    readOk+      [ ("cabal.project", "packages: b a/../b ./a/\n")+      , ("a/a.cabal", cabal "a" "GHC ^>= 9.10" False)+      , ("b/b.cabal", cabal "b" "GHC ^>= 9.10" False)+      ]+  assertEqual "two paths of a package" [(s 9 10, ["b", "a"])] (matrixOf twoPaths)+  -- A wildcard does not match the entries . and .. of a directory.+  dots <-+    readErrors+      [ ("cabal.project", "packages: .*/*.cabal\n")+      , ("up.cabal", cabal "up" "GHC ^>= 9.10" False)+      ]+  assertEqual+    "dot wildcard"+    ["PROJECT/cabal.project:1:11: the package location \".*/*.cabal\" matches no files."]+    dots+  current <-+    readOk+      [ ("cabal.project", "packages: .\n")+      , ("a.cabal", cabal "a" "GHC ^>= 9.10" False)+      ]+  assertEqual "the location ." [(s 9 10, ["a"])] (matrixOf current)++test_optional :: Assertion+test_optional = do+  project <-+    readOk+      [ ("cabal.project", "packages: a\noptional-packages: vendor/*/ docs/\n")+      , ("a/a.cabal", cabal "a" "GHC ^>= 9.10" False)+      , ("docs/index.md", "")+      ]+  assertEqual "packages" ["a"] (map (.name) project.packages)+  errors <-+    readErrors+      [ ("cabal.project", "packages: a\noptional-packages: vendor/* {broken\n")+      , ("a/a.cabal", cabal "a" "GHC ^>= 9.10" False)+      ]+  assertEqual+    "errors"+    ["PROJECT/cabal.project:2:29: the package location \"{broken\" is not a valid glob."]+    errors++test_exactAndSeries :: Assertion+test_exactAndSeries = do+  project <-+    readOk [("a.cabal", cabal "a" "GHC == { 9.6.7 } || ^>= 9.10 || == 9.12.2" False)]+  assertEqual "axis" [v [9, 6, 7], s 9 10, v [9, 12, 2]] (map fst $ matrixOf project)++test_exactNextToSeries :: Assertion+test_exactNextToSeries = do+  errors <-+    readErrors+      [ ("cabal.project", "packages: a b\n")+      , ("a/a.cabal", cabal "a" "GHC == 9.10.3" False)+      , ("b/b.cabal", cabal "b" "GHC ^>= 9.10" False)+      ]+  assertEqual+    "errors"+    [ "Package a lists only some versions of the GHC series 9.10 in tested-with, but another package lists the whole series. A conditional block in cabal.project cannot separate the two. Write the series in the same form in all packages, e.g. ^>= 9.10 or exact versions."+    ]+    errors++test_missingBlock :: Assertion+test_missingBlock = do+  errors <-+    readErrors+      [ ("cabal.project", "packages: core servant-client\n")+      , ("core/core.cabal", cabal "core" "GHC == 9.6.7 || ^>= 9.10 || ^>= 9.12" False)+      ,+        ( "servant-client/servant-client.cabal"+        , cabal "servant-client" "GHC ^>= 9.10 || ^>= 9.12" False+        )+      ]+  assertEqual+    "errors"+    [missingBlock "servant-client" "9.6.7" "^>=9.10 || ^>=9.12" "servant-client"]+    errors+  where+    missingBlock :: String -> String -> String -> FilePath -> String+    missingBlock package version range dir =+      unlines+        [ "Package "+            ++ package+            ++ " does not list GHC "+            ++ version+            ++ " in tested-with, but "+            ++ "PROJECT/cabal.project"+            ++ " includes it for that GHC version. Move the package to a conditional block in cabal.project, e.g.:"+        , ""+        , "if impl(ghc " ++ range ++ ")"+        , "  packages: " ++ dir+        ]++test_untestedVersion :: Assertion+test_untestedVersion = do+  errors <-+    readErrors+      [ ("cabal.project", "packages: a\nif impl(ghc >= 9.10)\n  packages: b\n")+      , ("a/a.cabal", cabal "a" "GHC ^>= 9.8 || ^>= 9.10" False)+      , ("b/b.cabal", cabal "b" "GHC ^>= 9.8 || ^>= 9.10" False)+      ]+  assertEqual+    "errors"+    [ "Package b lists GHC 9.8 in tested-with, but PROJECT/cabal.project does not include the package for that GHC version, so no job tests it. Remove the version from tested-with, or change the conditional block in cabal.project."+    ]+    errors++test_rootProject :: Assertion+test_rootProject =+  withSystemTempDirectory "haskell-gha-tests" $ \root -> do+    let write :: FilePath -> String -> IO ()+        write path contents = do+          createDirectoryIfMissing True (takeDirectory (root </> path))+          writeFile (root </> path) contents+    write "cabal.project" "packages: a\nif flag(dev)\n  packages: b\n"+    write "a/a.cabal" (cabal "a" "GHC ^>= 9.10" False)+    assertEqual+      "errors of the package locations"+      (Left ["cabal.project:3:13: the package location \"b\" does not exist."])+      =<< readProject root "."+    write "b/b.cabal" (cabal "b" "GHC ^>= 9.10" False)+    assertEqual+      "errors of the conditions"+      ( Left+          [ "cabal.project:2:1: the condition flag(dev) is not supported, because the tool does not know the value of the flag."+          ]+      )+      =<< readProject root "."++test_partialCondition :: Assertion+test_partialCondition = do+  errors <-+    readErrors+      [ ("cabal.project", "packages: a\nif impl(ghc >= 9.10.2)\n  packages: b\n")+      , ("a/a.cabal", cabal "a" "GHC ^>= 9.10" False)+      , ("b/b.cabal", cabal "b" "GHC ^>= 9.10" False)+      ]+  case errors of+    [e] ->+      assertBool+        e+        ( "the condition impl(ghc >=9.10.2) includes only a part of the GHC versions of the matrix entry 9.10"+            `L.isInfixOf` e+        )+    _ -> assertFailure (unlines errors)++test_firstRelease :: Assertion+test_firstRelease = do+  project <-+    readOk+      [+        ( "cabal.project"+        , "packages: a\nif impl(ghc >= 9.10.1)\n  packages: b\nif impl(ghc < 9.10.1)\n  packages: c\n"+        )+      , ("a/a.cabal", cabal "a" "GHC ^>= 9.10" False)+      , ("b/b.cabal", cabal "b" "GHC ^>= 9.10" False)+      , ("c/c.cabal", cabal "c" "GHC ^>= 9.10" False)+      ]+  assertEqual "matrix" [(s 9 10, ["a", "b"])] (matrixOf project)++test_flagCondition :: Assertion+test_flagCondition = do+  errors <-+    readErrors+      [ ("cabal.project", "packages: a\nif flag(dev)\n  packages: b\n")+      , ("a/a.cabal", cabal "a" "GHC ^>= 9.10" False)+      , ("b/b.cabal", cabal "b" "GHC ^>= 9.10" False)+      ]+  case errors of+    [e] -> assertBool e ("the condition flag(dev) is not supported" `L.isInfixOf` e)+    _ -> assertFailure (unlines errors)++test_projectFileErrors :: Assertion+test_projectFileErrors = do+  errors <-+    readErrors+      [+        ( "cabal.project"+        , "if foo(bar)\n  packages: a\nelse\n  packages: b\nelse\n  packages: c\n"+        )+      , ("a/a.cabal", cabal "a" "GHC ^>= 9.10" False)+      ]+  case errors of+    [condition, stray] -> do+      assertBool condition ("cabal.project:1:" `L.isInfixOf` condition)+      assertBool stray ("cabal.project:5:1: else without if" `L.isInfixOf` stray)+    _ -> assertFailure (unlines errors)+  elif <-+    readErrors+      [ ("cabal.project", "packages: a\nelif impl(ghc >= 9.10)\n  packages: b\n")+      , ("a/a.cabal", cabal "a" "GHC ^>= 9.10" False)+      ]+  assertEqual "elif without if" ["PROJECT/cabal.project:2:1: elif without if"] elif+  syntax <-+    readErrors+      [ ("cabal.project", "packages: a\n{\n")+      , ("a/a.cabal", cabal "a" "GHC ^>= 9.10" False)+      ]+  assertEqual+    "syntax error"+    ["PROJECT/cabal.project:2:1: expecting indentation of at least 1"]+    syntax+  unfinished <-+    readErrors+      [ ("cabal.project", "if impl(ghc\n  packages: a\n")+      , ("a/a.cabal", cabal "a" "GHC ^>= 9.10" False)+      ]+  -- Before Cabal-syntax 3.18, the parser of a condition does not know its+  -- position, and it gives this error the position 1:1.+  case unfinished of+    [e] ->+      assertBool+        e+        ( "PROJECT/cabal.project:1:" `L.isPrefixOf` e+            && ": unexpected end of input" `L.isSuffixOf` e+            && '\n' `notElem` e+        )+    _ -> assertFailure (unlines unfinished)++test_decidedCondition :: Assertion+test_decidedCondition = do+  project <-+    readOk+      [+        ( "cabal.project"+        , "packages: a\nif os(windows) && impl(ghc >= 9.10.2)\n  packages: b\nif flag(dev) || os(linux)\n  packages: c\n"+        )+      , ("a/a.cabal", cabal "a" "GHC ^>= 9.10" False)+      , ("b/b.cabal", cabal "b" "GHC ^>= 9.10" False)+      , ("c/c.cabal", cabal "c" "GHC ^>= 9.10" False)+      ]+  assertEqual "matrix" [(s 9 10, ["a", "c"])] (matrixOf project)++test_not :: Assertion+test_not = do+  project <-+    readOk+      [ ("cabal.project", "packages: a\nif !impl(ghc >= 9.12)\n  packages: b\n")+      , ("a/a.cabal", cabal "a" "GHC ^>= 9.10 || ^>= 9.12" False)+      , ("b/b.cabal", cabal "b" "GHC ^>= 9.10" False)+      ]+  assertEqual "matrix" [(s 9 10, ["a", "b"]), (s 9 12, ["a"])] (matrixOf project)++test_osArch :: Assertion+test_osArch = do+  project <-+    readOk+      [+        ( "cabal.project"+        , "packages: a\nif os(linux) && arch(x86_64)\n  packages: b\nif os(windows) || impl(ghcjs)\n  packages: c\n"+        )+      , ("a/a.cabal", cabal "a" "GHC ^>= 9.10" False)+      , ("b/b.cabal", cabal "b" "GHC ^>= 9.10" False)+      , ("c/c.cabal", cabal "c" "GHC ^>= 9.10" False)+      ]+  assertEqual "matrix" [(s 9 10, ["a", "b"])] (matrixOf project)++test_testedWithErrors :: Assertion+test_testedWithErrors = do+  openRange <- readErrors [("a.cabal", cabal "a" "GHC >= 9.10" False)]+  assertEqual+    "open range"+    [ "Package a lists the GHC range >=9.10 in tested-with. The matrix needs a finite list of versions. Write an exact version, e.g. == 9.10.3, or a major series, e.g. ^>= 9.10."+    ]+    openRange+  minorRange <- readErrors [("a.cabal", cabal "a" "GHC ^>= 9.10.2" False)]+  assertEqual+    "minor range"+    [ "Package a lists the GHC range >=9.10.2 && <9.11 in tested-with. A range must be a whole major series with two version parts, e.g. ^>= 9.10 or == 9.10.*. Write the series, or an exact version, e.g. == 9.10.3."+    ]+    minorRange+  shortVersion <- readErrors [("a.cabal", cabal "a" "GHC == 9.10" False)]+  assertEqual+    "short version"+    [ "Package a lists GHC == 9.10 in tested-with. No GHC release has this version. Write an exact version with three parts, e.g. == 9.10.3, or a major series, e.g. ^>= 9.10."+    ]+    shortVersion+  emptyRange <- readErrors [("a.cabal", cabal "a" "GHC == 9.10.1 && == 9.12.1" False)]+  assertEqual+    "empty range"+    [ "Package a lists the GHC range ==9.10.1 && ==9.12.1 in tested-with, which includes no version. Join the versions with ||, e.g. ^>= 9.10 || ^>= 9.12."+    ]+    emptyRange+  noGhc <- readErrors [("a.cabal", cabal "a" "GHCJS == 8.10.7" False)]+  assertEqual "no GHC" ["Package a has no GHC version in tested-with."] noGhc+  oldGhc <- readErrors [("a.cabal", cabal "a" "GHC == 8.8.4 || ^>= 9.0 || ^>= 8.6" False)]+  assertEqual+    "old GHC"+    [ "Package a lists GHC 8.6 in tested-with. The tool supports only GHC 8.10 and later. Remove the version from tested-with."+    , "Package a lists GHC 8.8.4 in tested-with. The tool supports only GHC 8.10 and later. Remove the version from tested-with."+    ]+    oldGhc+  oldestExact <- readOk [("a.cabal", cabal "a" "GHC == 8.10.7" False)]+  assertEqual "oldest exact GHC" [(v [8, 10, 7], ["a"])] (matrixOf oldestExact)+  oldestSeries <- readOk [("a.cabal", cabal "a" "GHC ^>= 8.10" False)]+  assertEqual "oldest GHC series" [(s 8 10, ["a"])] (matrixOf oldestSeries)++test_emptyEntry :: Assertion+test_emptyEntry = do+  errors <-+    readErrors+      [ ("cabal.project", "if impl(ghc >= 9.10)\n  packages: a\n")+      , ("a/a.cabal", cabal "a" "GHC == 9.6.7 || ^>= 9.10" False)+      ]+  case errors of+    [e] -> assertBool e ("cabal.project for GHC 9.6.7." `L.isSuffixOf` e)+    _ -> assertFailure (unlines errors)++test_locationErrors :: Assertion+test_locationErrors = do+  errors <-+    readErrors+      [+        ( "cabal.project"+        , unlines+            [ "packages: missing/ nothing/*.cabal https://example.com/a.tar.gz two docs/*"+            , "  /opt/pkg, ~/pkgs/*/"+            , "  ../../outside ../../*/*.cabal {broken"+            ]+        )+      , ("two/a.cabal", cabal "a" "GHC ^>= 9.10" False)+      , ("two/b.cabal", cabal "b" "GHC ^>= 9.10" False)+      , ("docs/a.md", "")+      , ("docs/pkg.tar.gz", "")+      ]+  assertEqual+    "errors"+    [ "PROJECT/cabal.project:1:11: the package location \"missing/\" does not exist."+    , "PROJECT/cabal.project:1:20: the package location \"nothing/*.cabal\" matches no files."+    , "PROJECT/cabal.project:1:36: the package location \"https://example.com/a.tar.gz\" is a URL. The tool supports only local packages."+    , "PROJECT/cabal.project:1:65: the directory \"two\" contains more than one .cabal file."+    , "PROJECT/cabal.project:1:69: the package location \"docs/pkg.tar.gz\" is a tarball. The tool supports only local packages."+    , "PROJECT/cabal.project:2:3: the package location \"/opt/pkg\" is not a relative path. The tool supports only packages in the repository."+    , "PROJECT/cabal.project:2:13: the package location \"~/pkgs/*/\" is not a relative path. The tool supports only packages in the repository."+    , "PROJECT/cabal.project:3:3: the package location \"../../outside\" is not in the repository. The tool supports only packages in the repository."+    , "PROJECT/cabal.project:3:17: the package location \"../../*/*.cabal\" is not in the repository. The tool supports only packages in the repository."+    , "PROJECT/cabal.project:3:33: the package location \"{broken\" is not a valid glob, and no file or directory has this path."+    ]+    errors+  noCabalFile <- readErrors [("cabal.project", "packages: docs/\n"), ("docs/a.md", "")]+  assertEqual+    "no .cabal file"+    ["PROJECT/cabal.project:1:11: the directory \"docs\" contains no .cabal file."]+    noCabalFile+  strayBrace <-+    readErrors+      [ ("cabal.project", "packages: a}b c\n")+      , ("c/c.cabal", cabal "c" "GHC ^>= 9.10" False)+      ]+  assertEqual+    "a stray brace"+    [ "PROJECT/cabal.project:1:11: the package location \"a}b\" is not a valid glob, and no file or directory has this path."+    ]+    strayBrace+  noPackages <- readErrors [("README", "")]+  assertEqual+    "no packages"+    ["There are no packages in the implicit project of \"PROJECT\"."]+    noPackages++test_doctestRootAndSubdirectory :: Assertion+test_doctestRootAndSubdirectory = do+  project <-+    readOk+      [+        ( "a.cabal"+        , unlines+            [ "cabal-version: 3.0"+            , "name: a"+            , "version: 0"+            , "tested-with: GHC ^>= 9.10"+            , "library"+            , "  hs-source-dirs: . src"+            , "  exposed-modules: Root Inner"+            ]+        )+      , ("Root.hs", "")+      , ("src/Inner.hs", "")+      , ("test/Main.hs", "")+      ]+  assertEqual+    "doctest arguments"+    [[["Root.hs", "src"]]]+    (map (.doctestArgs) project.packages)++test_doctestTrailingSeparator :: Assertion+test_doctestTrailingSeparator = do+  project <-+    readOk+      [+        ( "a.cabal"+        , unlines+            [ "cabal-version: 3.0"+            , "name: a"+            , "version: 0"+            , "tested-with: GHC ^>= 9.10"+            , "library"+            , "  hs-source-dirs: ./ src src/"+            , "  exposed-modules: Root Inner"+            ]+        )+      , ("Root.hs", "")+      , ("src/Inner.hs", "")+      , ("test/Main.hs", "")+      ]+  assertEqual+    "doctest arguments"+    [[["Root.hs", "src"]]]+    (map (.doctestArgs) project.packages)++----------------------------------------+-- Helpers++v :: [Int] -> GhcEntry+v = GhcExact . mkVersion++s :: Int -> Int -> GhcEntry+s = GhcSeries++matrixOf :: Project -> [(GhcEntry, [String])]+matrixOf project = [(e.ghc, map (.name) e.packages) | e <- project.matrix]++-- | The contents of a @.cabal@ file.+cabal :: String -> String -> Bool -> String+cabal name testedWith testSuite =+  unlines $+    [ "cabal-version: 3.0"+    , "name: " ++ name+    , "version: 0"+    , "tested-with: " ++ testedWith+    , "library"+    , "  exposed-modules: M"+    ]+      ++ if testSuite+        then ["test-suite test", "  type: exitcode-stdio-1.0", "  main-is: Main.hs"]+        else []++-- | Write the files of a project to a temporary directory and read it.+readProjectFiles :: [(FilePath, String)] -> IO (Either [String] Project)+readProjectFiles files =+  withSystemTempDirectory "haskell-gha-tests" $ \root -> do+    forM_ files $ \(path, contents) -> do+      createDirectoryIfMissing True (takeDirectory (root </> "PROJECT" </> path))+      writeFile (root </> "PROJECT" </> path) contents+    readProject root "PROJECT"++readOk :: [(FilePath, String)] -> IO Project+readOk files =+  readProjectFiles files >>= \case+    Left errors -> assertFailure (unlines errors)+    Right project -> pure project++readErrors :: [(FilePath, String)] -> IO [String]+readErrors files =+  readProjectFiles files >>= \case+    Left errors -> pure errors+    Right _ -> assertFailure "no errors"
+ tests/HaskellGha/Test/Workflow.hs view
@@ -0,0 +1,723 @@+module HaskellGha.Test.Workflow (workflowTests) where++import Control.Monad+import Data.ByteString qualified as BS+import Data.ByteString.Char8 qualified as BS8+import Data.Either+import Data.List qualified as L+import Data.Text qualified as T+import Data.Text.Encoding qualified as T+import Data.Time.Clock.POSIX+import Distribution.Version+import Options.Applicative+import System.Directory+import System.FilePath+import System.IO.Temp+import Test.Tasty+import Test.Tasty.HUnit+import Yamlet++import HaskellGha.Command+import HaskellGha.Command.Header+import HaskellGha.Command.Options+import HaskellGha.Config+import HaskellGha.Project+import HaskellGha.Workflow+import HaskellGha.Workflow.Script++workflowTests :: TestTree+workflowTests =+  testGroup+    "Workflow"+    [ testCase "a ghc value of the matrix that is not in the axis" test_unknownGhcValue+    , testCase "the dependencies axis" test_dependenciesAxis+    , testCase "a doctest range that includes a part of a series" test_partialDoctestRange+    , testCase "a range that includes no matrix entry" test_unusedRange+    , testCase "an unknown package in doctest.skip-packages" test_unknownSkip+    , testCase "the errors of independent checks are collected" test_independentChecks+    , testCase "the command line in the header" test_headerCommandLine+    , testCase "sdist with an import and a package outside the project" test_sdistOutside+    , testCase "an import outside the repository" test_importOutside+    , testCase "sdist with a package name that starts with another" test_sdistNamePrefix+    , testCase "a package directory with a space and a quote" test_scriptQuoting+    , testCase "the semaphore protocol of each cabal version" test_semaphoreVersions+    , testCase "several hlint paths" test_hlintPaths+    , testCase "a project directory outside the repository" test_projectDirOutside+    , testCase "a configuration file outside the repository" test_configOutside+    , testCase "an output file that GitHub does not read" test_outputPath+    , testCase "a control character or a line separator in a path option" test_controlCharacters+    , testCase "a named default configuration file" test_namedDefaultConfig+    , testCase "an hlint path outside the repository" test_hlintPathOutside+    , testCase "a hook step with the id of a step of the tool" test_hookStepId+    , testCase "the comments that the workflow keeps and drops" test_comments+    , testCase "the modes of the command line" test_modes+    , testCase "the generated workflows" test_findWorkflows+    , testCase "the commands write and check the workflow files" test_runCommand+    , testCase "symbolic links" test_symbolicLinks+    ]++test_comments :: Assertion+test_comments = do+  (config, source) <-+    either (assertFailure . unlines) pure . parseConfig "conf.yml" . BS8.pack $+      unlines+        [ "# The configuration."+        , ""+        , "# The permissions of the workflow."+        , "permissions: read-all # For the checkout."+        , "matrix:"+        , "  # The matrix."+        , ""+        , "  # The first axis."+        , "  os: [a, b]"+        , "  # The end of the matrix."+        , "tests: false"+        , "cabal-check: false"+        , "haddock: false"+        , ""+        , "# The jobs."+        , ""+        , "# The runner of the build."+        , "runs-on: ubuntu-24.04"+        , "fourmolu:"+        , "  version: 0.21.0.0"+        , "hooks:"+        , "  # The steps after the build."+        , "  after-build:"+        , "    # The step."+        , "    - run: echo a"+        , "    # A section."+        , ""+        , "    # The second step."+        , "    - run: echo b"+        , "    # The last lines."+        , "  # The end of the hooks."+        ]+  project <- readProject "tests/golden" "single" >>= either (assertFailure . unlines) pure+  node <-+    either (assertFailure . unlines) pure (workflow defaultOptions source config project)+  let rendered = T.lines $ renderWorkflow defaultOptions node+      assertLines preface ls = assertBool preface $ map T.pack ls `L.isInfixOf` rendered+  assertLines+    "top comment"+    ["# The permissions of the workflow.", "permissions: read-all # For the checkout."]+  assertBool "comment of the file" $ T.pack "# The configuration." `notElem` rendered+  assertBool "comment of a section" $ T.pack "    # The jobs." `notElem` rendered+  assertLines "matrix" ["      matrix:", "        # The matrix.", "", "        ghc:"]+  assertLines "first axis" ["        - '9.12'", "        # The first axis.", "        os:"]+  assertLines+    "end of the matrix"+    ["        - b", "        # The end of the matrix.", "    steps:"]+  assertLines "step" ["    # The step.", "    - run: echo a"]+  assertLines+    "second step"+    ["    - run: echo a", "", "    # The second step.", "    - run: echo b"]+  assertEqual+    "end of the steps"+    [T.pack "    - run: echo b"]+    (drop (length rendered - 1) rendered)+  assertBool "hook key" $ T.pack "    # The steps after the build." `notElem` rendered+  assertEqual+    "runs-on of the build job only"+    1+    (length (filter (== T.pack "    # The runner of the build.") rendered))++test_hlintPathOutside :: Assertion+test_hlintPathOutside = do+  assertErrors+    "hlint:\n  version: '3.10'\n  paths: [../x, /abs, a/../src]\n"+    [ "conf.yml:3:11: hlint.paths[0]: the path ../x is not in the repository. Give a path relative to the project directory."+    , "conf.yml:3:17: hlint.paths[1]: the path /abs is not in the repository. Give a path relative to the project directory."+    ]+  project <- readProject "tests/golden" "single" >>= either (assertFailure . unlines) pure+  (config, source) <-+    either (assertFailure . unlines) pure . parseConfig "conf.yml" $+      BS8.pack "hlint:\n  version: '3.10'\n  paths: [../x]\n"+  assertBool+    "in the repository"+    (isRight $ workflow defaultOptions {projectDir = "sub"} source config project)++test_hookStepId :: Assertion+test_hookStepId = do+  assertErrors+    "hooks:\n  after-setup:\n  - id: cache\n    run: echo a\n  after-build:\n  - id: Setup\n    run: echo b\n"+    [ "conf.yml:3:9: hooks.after-setup[0].id: the build job already has a step with the id cache. Give the hook step another id."+    , "conf.yml:6:9: hooks.after-build[0].id: the build job already has a step with the id setup, and GitHub compares the ids without case. Give the hook step another id."+    ]+  project <- readProject "tests/golden" "single" >>= either (assertFailure . unlines) pure+  (config, source) <-+    either (assertFailure . unlines) pure . parseConfig "conf.yml" $+      BS8.pack "hooks:\n  after-build:\n  - id: doctest\n    run: echo a\n"+  assertBool "without doctest" (isRight $ workflow defaultOptions source config project)++test_namedDefaultConfig :: Assertion+test_namedDefaultConfig = do+  let parse = parseOptions+  assertEqual "without --config" (Just DefaultConfigFile) ((.config) <$> parse [])+  assertEqual+    "with --config"+    (Just (ConfigFile defaultConfigPath))+    ((.config) <$> parse ["--config", defaultConfigPath])+  assertEqual+    "command line"+    (Just ["haskell-gha", "--generate", "--config", defaultConfigPath])+    (commandLine <$> parse ["--config", defaultConfigPath])++test_configOutside :: Assertion+test_configOutside = do+  let parse path = (.config) <$> parseOptions ["--config", path]+  assertEqual "sub" (Just (ConfigFile "a/../b.yml")) (parse "a/../b.yml")+  assertEqual "absolute" Nothing (parse "/tmp/conf.yml")+  assertEqual "parent" Nothing (parse "../conf.yml")++test_projectDirOutside :: Assertion+test_projectDirOutside = do+  let parse dir = parseOptions ["--project-dir", dir]+  assertEqual "sub" (Just "a/../b") ((.projectDir) <$> parse "a/../b")+  assertEqual "absolute" Nothing (parse "/tmp/project")+  assertEqual "parent" Nothing (parse "a/../../b")+  assertEqual "empty" Nothing (parse "")++test_outputPath :: Assertion+test_outputPath = do+  let parse name = (.output) <$> parseOptions ["--output", name]+  assertEqual "yml" (Just "a.yml") (parse "a.yml")+  assertEqual "yaml" (Just "a.yaml") (parse "a.yaml")+  assertEqual+    "path"+    (Just ".github/workflows/a.yml")+    (outputPath <$> parseOptions ["--output", "a.yml"])+  assertEqual "directory" Nothing (parse ".github/workflows/a.yml")+  assertEqual "current directory" Nothing (parse "./a.yml")+  assertEqual "absolute" Nothing (parse "/a.yml")+  assertEqual "extension" Nothing (parse "a.txt")+  assertEqual "comma" Nothing (parse "a,b.yml")++test_controlCharacters :: Assertion+test_controlCharacters =+  forM_ ["--config", "--project-dir", "--output"] $ \opt -> do+    assertEqual (opt ++ " empty") Nothing (parseOptions [opt, ""])+    assertEqual (opt ++ " with a line break") Nothing (parseOptions [opt, "a\nb"])+    assertEqual (opt ++ " with a tab") Nothing (parseOptions [opt, "a\tb"])+    assertEqual (opt ++ " with U+2028") Nothing (parseOptions [opt, "a\x2028\&b"])+    assertEqual (opt ++ " with U+2029") Nothing (parseOptions [opt, "a\x2029\&b"])++test_sdistNamePrefix :: Assertion+test_sdistNamePrefix = do+  project <- readProject "tests/golden" "single" >>= either (assertFailure . unlines) pure+  p <- case project.packages of+    [p] -> pure p+    ps -> assertFailure ("packages: " ++ show ps)+  let pkgs = [p {directory = "a"}, p {name = "example-2d", directory = "b"}]+      changed = project {packages = pkgs, matrix = [MatrixEntry e.ghc pkgs | e <- project.matrix]}+  node <-+    either+      (assertFailure . unlines)+      pure+      (workflow defaultOptions (emptySource "conf.yml") defaultConfig changed)+  assertEqual+    "tar lines"+    [ "tar -xzf \"$RUNNER_TEMP\"/haskell-gha-sdist/example-+([0-9.]).tar.gz --strip-components=1 -C \"$RUNNER_TEMP\"/haskell-gha/a"+    , "tar -xzf \"$RUNNER_TEMP\"/haskell-gha-sdist/example-2d-+([0-9.]).tar.gz --strip-components=1 -C \"$RUNNER_TEMP\"/haskell-gha/b"+    ]+    [ T.unpack (T.strip l)+    | l <- T.lines (renderWorkflow defaultOptions node)+    , T.pack "tar -xzf" `T.isInfixOf` l+    ]++test_scriptQuoting :: Assertion+test_scriptQuoting = do+  project <- readProject "tests/golden" "single" >>= either (assertFailure . unlines) pure+  p <- case project.packages of+    [p] -> pure p+    ps -> assertFailure ("packages: " ++ show ps)+  let q = p {directory = "my pkg's", doctestArgs = [["A.hs"]]}+      dir = T.pack "'my pkg'\\''s'"+      linesWith :: T.Text -> T.Text -> [T.Text]+      linesWith t = filter (T.isInfixOf t) . T.lines+  assertEqual+    "unpack"+    [ T.pack "mkdir -p \"$RUNNER_TEMP\"/haskell-gha/" <> dir+    , T.pack+        "tar -xzf \"$RUNNER_TEMP\"/haskell-gha-sdist/example-+([0-9.]).tar.gz --strip-components=1 -C \"$RUNNER_TEMP\"/haskell-gha/"+        <> dir+    ]+    (linesWith dir (unpackScript [q]))+  assertEqual "check" [T.pack "check example " <> dir] (linesWith dir (checkScript [q]))+  assertEqual+    "doctest"+    [T.pack "cd " <> dir, T.pack "\"$HOME\"/.local/bin/doctest A.hs"]+    (T.lines (doctestScript [] q))++test_semaphoreVersions :: Assertion+test_semaphoreVersions = do+  let script :: CabalVersion -> T.Text+      script = semaphoreScript 4+      both :: Int -> T.Text+      both n = T.pack ("GHC and cabal use version " ++ show n)+  assertBool+    "cabal 3.16"+    (both 1 `T.isInfixOf` script (CabalVersion (mkVersion [3, 16, 1, 0])))+  assertBool+    "cabal 3.18"+    (both 2 `T.isInfixOf` script (CabalVersion (mkVersion [3, 18, 1, 0])))+test_hlintPaths :: Assertion+test_hlintPaths = do+  (config, source) <-+    either (assertFailure . unlines) pure . parseConfig "conf.yml" $+      BS8.pack "hlint:\n  version: '3.10'\n  paths: [src, 'a\"b\\c']\n"+  project <- readProject "tests/golden" "single" >>= either (assertFailure . unlines) pure+  node <-+    either (assertFailure . unlines) pure (workflow defaultOptions source config project)+  assertEqual+    "path"+    [T.pack "path: '[\"src\", \"a\\\"b\\\\c\"]'"]+    [ T.strip l+    | l <- T.lines (renderWorkflow defaultOptions node)+    , T.pack "path: '[" `T.isInfixOf` l+    ]++test_sdistOutside :: Assertion+test_sdistOutside = do+  project <- readProject "tests/golden" "single" >>= either (assertFailure . unlines) pure+  p <- case project.packages of+    [p] -> pure p+    ps -> assertFailure ("packages: " ++ show ps)+  let changed =+        project+          { packages = [p {directory = "../lib"}, p {name = "inner", directory = "a/../b"}]+          , imports =+              [ Import+                  { location = "cabal.project:1:1: "+                  , target = "local.project"+                  }+              , Import+                  { location = "cabal.project:2:1: "+                  , target = "https://example.com/remote.project"+                  }+              ]+          }+  assertEqual+    "errors"+    ( Left+        [ "cabal.project:1:1: the workflow builds the source tarballs in a copy of the project directory, and the copy does not contain the imported file local.project. Set build-from: checkout in the configuration."+        , "Package example is in ../lib, outside the project directory, but the workflow builds the source tarballs in a copy of the project directory. Set build-from: checkout in the configuration."+        ]+    )+    (workflow defaultOptions (emptySource "conf.yml") defaultConfig changed)+  assertBool+    "build-from: checkout"+    ( isRight $+        workflow+          defaultOptions+          (emptySource "conf.yml")+          defaultConfig {buildFrom = BuildFromCheckout}+          changed+    )++test_importOutside :: Assertion+test_importOutside = do+  project <- readProject "tests/golden" "single" >>= either (assertFailure . unlines) pure+  let changed =+        project+          { imports =+              [ Import+                  { location = "cabal.project:1:1: "+                  , target = "../inside.project"+                  }+              , Import+                  { location = "cabal.project:2:1: "+                  , target = "../../outside.project"+                  }+              , Import+                  { location = "cabal.project:3:1: "+                  , target = "/etc/absolute.project"+                  }+              ]+          }+      opts = defaultOptions {projectDir = "sub"}+      outside =+        [ "cabal.project:2:1: the imported file ../../outside.project is not in the repository. Give a path relative to the project directory."+        , "cabal.project:3:1: the imported file /etc/absolute.project is not in the repository. Give a path relative to the project directory."+        ]+  assertEqual+    "build-from: tarballs"+    ( Left $+        "cabal.project:1:1: the workflow builds the source tarballs in a copy of the project directory, and the copy does not contain the imported file ../inside.project. Set build-from: checkout in the configuration."+          : outside+    )+    (workflow opts (emptySource "conf.yml") defaultConfig changed)+  assertEqual+    "build-from: checkout"+    (Left outside)+    ( workflow+        opts+        (emptySource "conf.yml")+        defaultConfig {buildFrom = BuildFromCheckout}+        changed+    )++test_headerCommandLine :: Assertion+test_headerCommandLine = do+  let opts = defaultOptions {projectDir = "my project", output = "it's.yml"}+      line =+        T.unpack+          <$> L.find+            (T.isInfixOf (T.pack "haskell-gha --"))+            (T.lines $ renderWorkflow opts (mapping []))+  assertEqual+    "command line"+    (Just "#   haskell-gha --generate --project-dir 'my project' --output 'it'\\''s.yml'")+    line++test_unknownGhcValue :: Assertion+test_unknownGhcValue =+  assertErrors+    "matrix:\n  x: [a, b]\n  exclude:\n    - ghc: '9.8'\n      x: a\n"+    [ "conf.yml:4:12: matrix.exclude[0].ghc: GHC 9.8 is not in the ghc axis, which contains only 9.6.7, 9.10, 9.12"+    ]++test_dependenciesAxis :: Assertion+test_dependenciesAxis = do+  assertErrors+    "dependencies: both\nmatrix:\n  dependencies: [a, b]\n  exclude:\n    - dependencies: older\n"+    [ "conf.yml:3:3: matrix: the tool makes the dependencies axis for dependencies: both, so the matrix must not contain it"+    , "conf.yml:5:21: matrix.exclude[0].dependencies: dependencies older is not in the dependencies axis, which contains only newest, oldest"+    ]+  assertErrors+    "matrix:\n  exclude:\n    - dependencies: oldest\n"+    [ "conf.yml:3:21: matrix.exclude[0].dependencies: the matrix has no dependencies axis. Set dependencies: both to add it."+    ]+  assertValid+    "dependencies: both\nmatrix:\n  exclude:\n    - ghc: '9.10'\n      dependencies: oldest\n"+  assertValid "matrix:\n  dependencies: [a, b]\n  exclude:\n    - dependencies: a\n"+  where+    assertValid :: String -> Assertion+    assertValid input = do+      (config, source) <-+        either (assertFailure . unlines) pure . parseConfig "conf.yml" $ BS8.pack input+      project <- readProject "tests/golden" "single" >>= either (assertFailure . unlines) pure+      either+        (assertFailure . unlines)+        (const (pure ()))+        (workflow defaultOptions source config project)++test_partialDoctestRange :: Assertion+test_partialDoctestRange =+  assertErrors+    "doctest:\n  ghc: '>=9.10.2'\n"+    [ "conf.yml:2:8: doctest.ghc: the range >=9.10.2 includes only a part of the GHC versions of the matrix entry 9.10, so the result depends on the minor version that GHCup selects. Change the range, or write exact versions in tested-with."+    ]++test_unusedRange :: Assertion+test_unusedRange =+  assertErrors+    "doctest:\n  ghc: '>=9.14'\n"+    [ "conf.yml:2:8: doctest.ghc: the range >=9.14 includes no GHC version of the matrix, which contains only 9.6.7, 9.10, 9.12"+    ]++test_independentChecks :: Assertion+test_independentChecks =+  assertErrors+    "doctest:\n  skip-packages: [other]\nhlint:\n  version: '3.10'\n  paths: [../x]\n"+    [ "conf.yml:2:19: doctest.skip-packages[0]: the project has no local package other"+    , "conf.yml:5:11: hlint.paths[0]: the path ../x is not in the repository. Give a path relative to the project directory."+    ]++test_unknownSkip :: Assertion+test_unknownSkip =+  assertErrors+    "doctest:\n  skip-packages: [other]\n"+    ["conf.yml:2:19: doctest.skip-packages[0]: the project has no local package other"]++-- | The first lines of the errors for a configuration and the project of the+-- golden test @single@. The other lines show the line of the configuration.+assertErrors :: String -> [String] -> Assertion+assertErrors input expected = do+  (config, source) <-+    either (assertFailure . unlines) pure . parseConfig "conf.yml" $ BS8.pack input+  project <- readProject "tests/golden" "single" >>= either (assertFailure . unlines) pure+  assertEqual+    "errors"+    (Left expected)+    ( either+        (Left . map (takeWhile (/= '\n')))+        Right+        (workflow defaultOptions source config project)+    )++test_modes :: Assertion+test_modes = do+  let parse = getParseResult . execParserPure defaultPrefs (optionsParser "TEST")+  assertEqual "no options" (Just Regenerate) (parse [])+  assertEqual "--check" (Just Check) (parse ["--check"])+  assertEqual "--generate" (Just (Generate defaultOptions)) (parse ["--generate"])+  assertEqual "--generate --check" Nothing (parse ["--generate", "--check"])+  assertEqual "--output without --generate" Nothing (parse ["--output", "a.yml"])++test_findWorkflows :: Assertion+test_findWorkflows =+  withSystemTempDirectory "haskell-gha-tests" $ \root -> do+    let dir = workflowDirectory+        opts =+          defaultOptions+            { config = ConfigFile "it's.yml"+            , projectDir = "my project"+            , output = "a.yml"+            }+        write :: FilePath -> T.Text -> IO ()+        write name = BS.writeFile (root </> dir </> name) . T.encodeUtf8+    assertEqual+      "no directory"+      ( Left+          [ "No workflow in "+              ++ dir+              ++ " was generated by haskell-gha. To generate one, run haskell-gha --generate."+          ]+      )+      =<< findWorkflows root+    createDirectoryIfMissing True (root </> dir)+    write "a.yml" $ renderWorkflow opts (mapping [])+    write "b.yml" (T.pack "name: other\n")+    createDirectory (root </> dir </> "directory.yml")+    createFileLink (root </> dir </> "missing") (root </> dir </> "dangling.yml")+    assertEqual "generated workflow" (Right [opts]) =<< findWorkflows root+    write "c.yaml" $ renderWorkflow opts {output = "d.yml"} (mapping [])+    assertEqual+      "other output"+      ( Left+          [ dir+              </> "c.yaml"+              ++ ": the command in the header writes the workflow to "+              ++ dir+              </> "d.yml"+              ++ ", not to this file"+          ]+      )+      =<< findWorkflows root+    let withCommand :: String -> IO ()+        withCommand line =+          write "c.yaml"+            . T.unlines+            . zipWith (\i l -> if i == 1 then T.pack ("#   " ++ line) else l) [0 :: Int ..]+            . T.lines+            $ renderWorkflow opts (mapping [])+        firstLines :: Either [String] a -> Either [String] a+        firstLines = either (Left . map (takeWhile (/= '\n'))) Right+    withCommand "echo haskell-gha"+    assertEqual+      "other program"+      ( Left+          [ dir+              </> "c.yaml"+              ++ ": the command in the header is not valid: the command does not start with haskell-gha --generate"+          ]+      )+      =<< findWorkflows root+    withCommand "haskell-gha --generate --output c.yaml --foo"+    assertEqual+      "unknown option"+      ( Left+          [dir </> "c.yaml" ++ ": the command in the header is not valid: Invalid option `--foo'"]+      )+      . firstLines+      =<< findWorkflows root+    withCommand "haskell-gha --generate --output 'c.yaml"+    assertEqual+      "unclosed quote"+      ( Left+          [dir </> "c.yaml" ++ ": the command in the header has a quote without its end"]+      )+      =<< findWorkflows root+    let noCommand =+          Left [dir </> "c.yaml" ++ ": the header has no command on its second line"]+    write "c.yaml" $+      T.pack "# Do not edit this file, it was generated by the following command:\n"+    assertEqual "only the marker" noCommand =<< findWorkflows root+    write "c.yaml" $+      T.pack "# Do not edit this file, it was generated by the following command:\nname: x\n"+    assertEqual "no comment after the marker" noCommand =<< findWorkflows root++test_symbolicLinks :: Assertion+test_symbolicLinks =+  withSystemTempDirectory "haskell-gha-tests" $ \tmp -> do+    let root = tmp </> "repo"+        outside = tmp </> "outside"+        writePackage :: FilePath -> IO ()+        writePackage dir = do+          createDirectoryIfMissing True dir+          writeFile (dir </> "a.cabal") . unlines $+            [ "cabal-version: 3.0"+            , "name: a"+            , "version: 0"+            , "tested-with: GHC ^>= 9.10"+            , "library"+            ]+        -- Without the excerpts of the configuration.+        errors :: Options -> IO (Either [String] ())+        errors = fmap (either (Left . map (takeWhile (/= '\n'))) (const (Right ()))) . generate root+        throughLink :: String -> String+        throughLink start = start ++ " leads out of the repository through a symbolic link."+    writePackage (root </> "real")+    createDirectory (root </> ".git")+    writePackage (outside </> "project")+    writeFile (outside </> "conf.yml") ""+    writeFile (outside </> "cabal.project") "packages: .\n"+    writeFile (root </> "real" </> "conf.yml") ""+    createFileLink "../outside/conf.yml" (root </> "out.yml")+    createDirectoryLink "../outside/project" (root </> "out")+    createDirectoryLink ".." (root </> "up")+    createFileLink (outside </> "conf.yml") (root </> "absolute.yml")+    createFileLink "loop.yml" (root </> "loop.yml")+    createFileLink "real/conf.yml" (root </> "in.yml")+    createDirectoryLink "real" (root </> "in")++    assertEqual "links in the repository" (Right ())+      =<< errors defaultOptions {config = ConfigFile "in.yml", projectDir = "in"}+    assertEqual+      "links out of the repository"+      ( Left+          [ throughLink "The configuration file out.yml"+          , throughLink "The project directory out"+          ]+      )+      =<< errors defaultOptions {config = ConfigFile "out.yml", projectDir = "out"}+    assertEqual+      "a link to the parent directory"+      (Left [throughLink "The project directory up"])+      =<< errors defaultOptions {projectDir = "up"}+    assertEqual+      "an absolute target"+      ( Left+          [ "The configuration file absolute.yml goes through the symbolic link absolute.yml with an absolute target, but the repository is at another place on the runner. Give the link a relative target."+          ]+      )+      =<< errors defaultOptions {config = ConfigFile "absolute.yml", projectDir = "real"}+    assertEqual+      "a loop"+      ( Left+          [ "The configuration file loop.yml goes through more than 40 symbolic links, and Linux on the runner follows no more."+          ]+      )+      =<< errors defaultOptions {config = ConfigFile "loop.yml", projectDir = "real"}++    createDirectory (root </> "linked")+    createFileLink "../../outside/cabal.project" (root </> "linked" </> "cabal.project")+    assertEqual+      "the project file"+      (Left [throughLink "The project file linked/cabal.project"])+      =<< errors defaultOptions {projectDir = "linked"}++    createDirectory (root </> "proj")+    writeFile (root </> "proj" </> "cabal.project") "packages: pkg\nimport: ../out.yml\n"+    createDirectoryLink "../../outside/project" (root </> "proj" </> "pkg")+    assertEqual+      "a package file"+      (Left [throughLink "The package file proj/pkg/a.cabal"])+      =<< errors defaultOptions {projectDir = "proj"}++    removeDirectoryLink (root </> "proj" </> "pkg")+    createDirectoryLink "../real" (root </> "proj" </> "pkg")+    writeFile+      (root </> "proj" </> "conf.yml")+      "build-from: checkout\nhlint:\n  version: '3.10'\n  paths: [../out]\n"+    assertEqual+      "the paths on the runner"+      ( Left+          [ throughLink "proj/conf.yml:4:11: hlint.paths[0]: the path ../out"+          , throughLink "proj/cabal.project:2:1: the imported file ../out.yml"+          ]+      )+      =<< errors defaultOptions {config = ConfigFile "proj/conf.yml", projectDir = "proj"}++    createDirectoryIfMissing True (root </> workflowDirectory)+    createFileLink "../../../outside/new.yml" (root </> outputPath defaultOptions)+    assertEqual+      "a broken link at the output"+      [throughLink ("The workflow " ++ outputPath defaultOptions)]+      =<< runCommand root (Generate defaultOptions {projectDir = "real"})+    assertBool "no file outside" . not =<< doesPathExist (outside </> "new.yml")++test_runCommand :: Assertion+test_runCommand =+  withSystemTempDirectory "haskell-gha-tests" $ \root -> do+    let writePackage :: IO ()+        writePackage =+          writeFile (root </> "a.cabal") . unlines $+            [ "cabal-version: 3.0"+            , "name: a"+            , "version: 0"+            , "tested-with: GHC ^>= 9.10"+            , "library"+            ]+    writePackage+    let run :: Command -> IO [String]+        run = runCommand root+    assertEqual+      "--generate outside the root"+      [ "The current directory has no .git, so it is not the root of a repository. GitHub reads only the workflows in "+          ++ workflowDirectory+          ++ " of the root, so run haskell-gha --generate there."+      ]+      =<< run (Generate defaultOptions)+    assertBool "no workflow outside the root" . not+      =<< doesPathExist (root </> workflowDirectory)+    createDirectory (root </> ".git")+    let output :: FilePath+        output = root </> outputPath defaultOptions+        old = posixSecondsToUTCTime 0+        notUpToDate =+          [ "The workflow "+              ++ outputPath defaultOptions+              ++ " is not up to date. To update it, run haskell-gha without --check."+          ]+    assertEqual "first --generate" [] =<< run (Generate defaultOptions)+    assertBool "workflow written" =<< doesFileExist output+    assertEqual "--check after --generate" [] =<< run Check+    setModificationTime output old+    assertEqual "second --generate" [] =<< run (Generate defaultOptions)+    assertEqual "regenerate" [] =<< run Regenerate+    assertEqual "mtime of an unchanged workflow" old =<< getModificationTime output+    appendFile output "# An edit.\n"+    assertEqual "--check after an edit" notUpToDate =<< run Check+    assertEqual "regenerate after an edit" [] =<< run Regenerate+    assertEqual "--check after regenerate" [] =<< run Check+    removeFile (root </> "a.cabal")+    let noPackages = "There are no packages in the implicit project of \".\"."+    assertEqual "error" [noPackages] =<< run (Generate defaultOptions)+    let named = [outputPath defaultOptions ++ ": " ++ noPackages]+    assertEqual "error of regenerate" named =<< run Regenerate+    assertEqual "error of --check" named =<< run Check+    writePackage+    let ci = root </> workflowDirectory </> "ci.yml"+        ciOptions = defaultOptions {output = "ci.yml"}+    writeFile ci "name: CI\n"+    assertEqual+      "--generate over a workflow that the tool did not generate"+      [ "The workflow "+          ++ outputPath ciOptions+          ++ " was not generated by haskell-gha, so the tool does not replace it. Delete the file first, or give another name with --output."+      ]+      =<< run (Generate ciOptions)+    assertEqual "the workflow that the tool did not generate" "name: CI\n" =<< readFile ci+    writeFile ci "# Do not edit this file, it was generated by the following command:\n"+    assertEqual "--generate over a broken header" [] =<< run (Generate ciOptions)+    assertBool "the repaired header" . either (const False) (elem ciOptions)+      =<< findWorkflows root+    removeFile ci+    let dirOptions = defaultOptions {output = "dir.yml"}+    createDirectory (root </> outputPath dirOptions)+    assertEqual+      "--generate over a directory"+      [ "The workflow "+          ++ outputPath dirOptions+          ++ " is a directory, so the tool does not replace it. Delete the directory first, or give another name with --output."+      ]+      =<< run (Generate dirOptions)+    assertEqual "regenerate next to a directory" [] =<< run Regenerate++-- | The options of a command line for one workflow, after @--generate@.+parseOptions :: [String] -> Maybe Options+parseOptions args = case getParseResult $ execParserPure defaultPrefs (optionsParser "TEST") ("--generate" : args) of+  Just (Generate opts) -> Just opts+  _ -> Nothing
+ tests/HaskellGha/Test/Yaml.hs view
@@ -0,0 +1,192 @@+module HaskellGha.Test.Yaml (yamlTests) where++import Data.Text qualified as T+import Test.Tasty+import Test.Tasty.HUnit+import Yamlet+import Yamlet.Syntax++import HaskellGha.Test.Helpers+import HaskellGha.Yaml++yamlTests :: TestTree+yamlTests =+  testGroup+    "Yaml"+    [ testCase "styles and key order survive a round trip" test_styles+    , testCase "flow collections become block collections" test_flow+    , testCase "comments survive a round trip" test_comments+    , testCase "empty lines" test_emptyLines+    , testCase "the output parses to the same tree" test_reparse+    , testCase "a comment above the first key after the header" test_header+    , testCase "trailing empty lines of a block scalar" test_keep+    , testCase "a plain scalar that needs quotes" test_plainQuotes+    ]++test_styles :: Assertion+test_styles =+  assertRoundTrip $+    T.unlines+      [ "zeta: plain"+      , "alpha: 'single: quoted'"+      , "beta: \"double\""+      , "run: |"+      , "  echo a"+      , "  echo b"+      , "strip: |-"+      , "  no newline"+      , "version: '9.10'"+      , "number: 9.10"+      , "empty:"+      , "steps:"+      , "- uses: actions/checkout@v7"+      , "  with:"+      , "    key: ${{ runner.os }}-ghc"+      ]++test_flow :: Assertion+test_flow = do+  node <- parse "branches: [master, main]\nports: ['5432:5432']\nnone: []\n"+  assertEqual+    "rendered"+    (T.unlines ["branches:", "- master", "- main", "ports:", "- '5432:5432'", "none: []"])+    (render node)++test_comments :: Assertion+test_comments =+  assertRoundTrip $+    T.unlines+      [ "# before a key"+      , "services:"+      , "  # first entry"+      , "  postgres:"+      , "    image: postgres # end of line"+      , "hooks:"+      , "- run: a"+      , "# between items"+      , "- run: b"+      , "# at the end"+      ]++test_emptyLines :: Assertion+test_emptyLines = do+  let node =+        mapping+          [ "name" .= plain "CI"+          , "steps" .= sequenceNode [plain "a", plain "b"]+          , "more" .= sequenceNode [plain "c", plain "d"]+          ]+  assertEqual+    "rendered"+    ( T.unlines+        ["# header", "", "name: CI", "", "steps:", "- a", "", "- b", "", "more:", "- c", "- d"]+    )+    (renderDocument ["header"] separated node)+  where+    separated :: [T.Text] -> Bool+    separated = \case+      [] -> True+      ["steps"] -> True+      _ -> False++test_reparse :: Assertion+test_reparse = do+  let node =+        mapping+          [ "on"+              .= mapping+                [ "push" .= mapping ["branches" .= sequenceNode [plain "master"]]+                , "pull_request" .= plain ""+                ]+          , "run" .= literal "cabal build all\ncabal test all\n"+          , "ghc" .= sequenceNode [singleQuoted "9.10", singleQuoted "it's"]+          ]+  reparsed <- parse $ renderDocument ["header"] (const True) node+  assertEqual "reparsed tree" node (normalize reparsed)++test_header :: Assertion+test_header = do+  let node = mapping [(addBefore [Comment "the name"] (plain "name"), plain "CI")]+  assertEqual+    "rendered"+    (T.unlines ["# header", "", "# the name", "name: CI"])+    (renderDocument ["header"] (const False) node)++test_keep :: Assertion+test_keep = do+  let node = mapping ["run" .= literal "echo a\n\n", "next" .= plain "b"]+  reparsed <- parse $ renderDocument [] (const True) node+  assertEqual "reparsed tree" node (normalize reparsed)++test_plainQuotes :: Assertion+test_plainQuotes = do+  let texts =+        [ "my dir: x"+        , "dir #1"+        , "[x]"+        , "*x"+        , "&x"+        , "- x"+        , " x"+        , "x "+        , "x:"+        , "'x"+        , "a\tb"+        , ""+        , "~"+        , "null"+        , "true"+        , "False"+        , "1"+        , "1.0"+        , "0x1F"+        , ".inf"+        ]+      node = sequenceNode (map plain texts)+  reparsed <- parse $ render node+  assertEqual "texts" (sequenceNode [singleQuoted t | t <- texts]) (normalize reparsed)+  assertEqual+    "plain"+    [ scalarNode Plain t+    | t <-+        [ "sub/dir"+        , "-x"+        , "a:b"+        , "a#b"+        , "yes"+        , "1.0.0"+        , "9.10.3"+        , "${{ matrix.ghc }}"+        , "contains(fromJSON('[\"9.10\"]'), matrix.ghc)"+        ]+    ]+    ( map+        plain+        [ "sub/dir"+        , "-x"+        , "a:b"+        , "a#b"+        , "yes"+        , "1.0.0"+        , "9.10.3"+        , "${{ matrix.ghc }}"+        , "contains(fromJSON('[\"9.10\"]'), matrix.ghc)"+        ]+    )++----------------------------------------+-- Helpers++parse :: T.Text -> IO Node+parse input = case decodeText @(Maybe Node) input of+  Left errors -> assertFailure $ foldMap ((++ "\n") . prettyError "input") errors+  Right Nothing -> assertFailure "no document"+  Right (Just node) -> pure node++render :: Node -> T.Text+render = renderDocument [] (const False)++assertRoundTrip :: T.Text -> Assertion+assertRoundTrip input = do+  node <- parse input+  assertEqual "rendered" input (render node)
+ tests/Main.hs view
@@ -0,0 +1,22 @@+module Main (main) where++import Test.Tasty++import HaskellGha.Test.Config+import HaskellGha.Test.Golden+import HaskellGha.Test.Project+import HaskellGha.Test.Workflow+import HaskellGha.Test.Yaml++main :: IO ()+main = do+  golden <- goldenTests+  defaultMain $+    testGroup+      "haskell-gha"+      [ yamlTests+      , configTests+      , projectTests+      , workflowTests+      , golden+      ]
+ tests/golden/checkout/checkout.cabal view
@@ -0,0 +1,9 @@+cabal-version: 3.0+name: checkout+version: 0+tested-with: GHC ^>= { 9.10, 9.12 }+library+  exposed-modules: M+test-suite test+  type: exitcode-stdio-1.0+  main-is: Main.hs
+ tests/golden/checkout/expected.yaml view
@@ -0,0 +1,151 @@+# Do not edit this file, it was generated by the following command:+#   haskell-gha --generate --config haskell-gha.conf.yaml+#+# To regenerate it, run from the root of the repository:+#   haskell-gha+#+# For more information, see https://github.com/arybczak/haskell-gha++name: CI++on:+  push:+    branches:+    - master+    - main+  pull_request:+  merge_group:+  workflow_dispatch:++permissions:+  contents: read++concurrency:+  group: ${{ github.workflow_ref }}+  cancel-in-progress: true++defaults:+  run:+    shell: bash++jobs:+  build:+    name: GHC ${{ matrix.ghc }}+    runs-on: ubuntu-26.04+    timeout-minutes: 60+    strategy:+      fail-fast: false+      matrix:+        ghc:+        - '9.10'+        - '9.12'+    steps:+    - uses: actions/checkout@v7+      with:+        persist-credentials: false++    - name: Install GHC and cabal+      id: setup+      run: |+        mkdir -p "$RUNNER_TEMP"/.ghcup/bin+        curl -fsSL -o "$RUNNER_TEMP"/.ghcup/bin/ghcup "https://downloads.haskell.org/ghcup/$(uname -m)-linux-ghcup"+        chmod +x "$RUNNER_TEMP"/.ghcup/bin/ghcup+        export GHCUP_INSTALL_BASE_PREFIX="$RUNNER_TEMP" PATH="$RUNNER_TEMP/.ghcup/bin:$PATH"+        echo "GHCUP_INSTALL_BASE_PREFIX=$RUNNER_TEMP" >> "$GITHUB_ENV"+        echo "$RUNNER_TEMP/.ghcup/bin" >> "$GITHUB_PATH"+        versions=$(ghcup -s vanilla list -t ghc -r)+        if grep -qF -e 'ghc ${{ matrix.ghc }} ' -e 'ghc ${{ matrix.ghc }}.' <<< "$versions"; then+          channel=vanilla+        else+          echo 'The vanilla channel of GHCup has no GHC ${{ matrix.ghc }}, so the step uses the prerelease channel.'+          channel=prereleases+        fi+        ghcup -s "$channel" install ghc '${{ matrix.ghc }}' --set+        ghcup -s vanilla install cabal 3.16.1.0 --set+        cabal update+        echo "ghc-version=$(ghc --numeric-version)" >> "$GITHUB_OUTPUT"+        echo "cabal-version=$(cabal --numeric-version)" >> "$GITHUB_OUTPUT"+        echo "cabal-store=$(cabal path -z --store-dir)" >> "$GITHUB_OUTPUT"++    - name: Show the versions+      id: versions+      run: |+        ghc --version+        cabal --version+        echo "GHC ${{ steps.setup.outputs.ghc-version }}, cabal ${{ steps.setup.outputs.cabal-version }}, image $ImageOS $ImageVersion" >> "$GITHUB_STEP_SUMMARY"+        echo "image=$ImageOS" >> "$GITHUB_OUTPUT"++    - name: Configure the project+      run: |+        if [ -f cabal.project.local ]; then+          echo '::error::The repository contains cabal.project.local, which holds the settings of one developer. Move the settings to cabal.project or to the key cabal-project-local of the configuration of haskell-gha, and remove the file from the repository.'+          exit 1+        fi+        cat >> cabal.project.local <<'EOF'+        jobs: 4+        tests: True+        benchmarks: True++        program-options+          ghc-options: -Werror+        EOF++    - name: Enable the GHC job semaphore or parallel module builds+      run: |+        if ghc --info | grep -F '("Semaphore version","2")' > /dev/null; then+        echo 'GHC uses version 2 of the semaphore protocol and cabal version 1, so GHC uses -j4.'+        cat >> cabal.project.local <<'EOF'+        program-options+          ghc-options: -j4+        EOF+        else+        echo 'GHC and cabal use version 1 of the semaphore protocol, so GHC uses the semaphore.'+        cat >> cabal.project.local <<'EOF'+        semaphore: True+        EOF+        fi++    - name: Make the build plan+      id: plan+      run: |+        cabal build all --dry-run+        echo "hash=$(sha256sum dist-newstyle/cache/plan.json | cut -d ' ' -f 1)" >> "$GITHUB_OUTPUT"++    - uses: actions/cache/restore@v6+      id: cache+      with:+        path: ${{ steps.setup.outputs.cabal-store }}+        key: haskell-gha.yaml-v1-${{ runner.os }}-${{ runner.arch }}-${{ steps.versions.outputs.image }}-ghc-${{ steps.setup.outputs.ghc-version }}-newest-${{ steps.plan.outputs.hash }}+        restore-keys: haskell-gha.yaml-v1-${{ runner.os }}-${{ runner.arch }}-${{ steps.versions.outputs.image }}-ghc-${{ steps.setup.outputs.ghc-version }}-newest-++    - name: Build the dependencies+      run: |+        cabal build all --only-dependencies++    - uses: actions/cache/save@v6+      if: steps.cache.outputs.cache-hit != 'true'+      with:+        path: ${{ steps.setup.outputs.cabal-store }}+        key: ${{ steps.cache.outputs.cache-primary-key }}++    - name: Build+      run: |+        cabal build all++    - name: Run the tests+      run: |+        cabal test all --test-show-details=direct++    - name: Check the packages+      run: |+        failed=0+        check() {+          echo "Checking the package $1"+          (cd "$2" && cabal check) || { echo "::error::cabal check failed for the package $1"; failed=1; }+        }+        check checkout .+        exit "$failed"++    - name: Build the documentation+      run: |+        cabal haddock all --disable-documentation --haddock-for-hackage
+ tests/golden/checkout/haskell-gha.conf.yaml view
@@ -0,0 +1,1 @@+build-from: checkout
+ tests/golden/config/config.cabal view
@@ -0,0 +1,11 @@+cabal-version: 3.0+name:          config+version:       0+tested-with:   GHC ^>= { 9.10, 9.12 }++library+  exposed-modules: Config++test-suite test+  type:    exitcode-stdio-1.0+  main-is: Main.hs
+ tests/golden/config/expected.yaml view
@@ -0,0 +1,252 @@+# Do not edit this file, it was generated by the following command:+#   haskell-gha --generate --config haskell-gha.conf.yaml+#+# To regenerate it, run from the root of the repository:+#   haskell-gha+#+# For more information, see https://github.com/arybczak/haskell-gha++name: Postgres CI++on:+  push:+    branches:+    - master+    - release/**+  pull_request:+  merge_group:+  workflow_dispatch:++# The test reporter writes check runs.+permissions:+  contents: read+  # For the annotations of the test results.+  checks: write++concurrency:+  group: ${{ github.workflow_ref }}+  cancel-in-progress: true++defaults:+  run:+    shell: bash++jobs:+  fourmolu:+    name: Fourmolu+    runs-on:+      group: small+      labels:+      - self-hosted+      - linux+    timeout-minutes: 90+    steps:+    - uses: actions/checkout@v6+      with:+        persist-credentials: false++    - uses: haskell-actions/run-fourmolu@v12+      with:+        version: '0.19.0.1'+        pattern: |+          src/**/*.hs+          !src/Generated.hs++  hlint:+    name: HLint+    # HLint needs no large runner.+    runs-on: ubuntu-slim+    timeout-minutes: 90+    steps:+    - uses: actions/checkout@v6+      with:+        persist-credentials: false++    - uses: haskell-actions/hlint-setup@v2+      with:+        version: '3.8'++    - uses: haskell-actions/hlint-run@v2+      with:+        path: '["src", "test"]'+        fail-on: error++  build:+    name: 'GHC ${{ matrix.ghc }}, ${{ matrix.dependencies }}, postgres ${{ matrix.postgres }}'+    runs-on: ubuntu-24.04+    timeout-minutes: 90+    # The services of each build job.+    services:+      # The database for the tests.+      postgres:+        image: postgres:${{ matrix.postgres }}+        env:+          POSTGRES_PASSWORD: postgres # Only for CI.+        ports:+        - '5432:5432'+        # The runner starts the steps when the database accepts connections.+        options: >-+          --health-cmd pg_isready+          --health-interval 5s+          --health-retries 10+    strategy:+      fail-fast: false+      # The oldest and the newest supported Postgres.+      matrix:+        ghc:+        - '9.10'+        - '9.12'+        dependencies:+        - newest+        - oldest+        postgres:+        - '15'+        - '18'+        exclude:+        - ghc: '9.10'+          postgres: '15'+    steps:+    - uses: actions/checkout@v6+      with:+        persist-credentials: false+        submodules: recursive++    - name: Install the system packages+      run: |+        sudo apt-get update+        sudo DEBIAN_FRONTEND=noninteractive apt-get install -y --no-install-recommends libpq-dev postgresql-client++    - name: Install GHC and cabal+      id: setup+      run: |+        mkdir -p "$RUNNER_TEMP"/.ghcup/bin+        curl -fsSL -o "$RUNNER_TEMP"/.ghcup/bin/ghcup "https://downloads.haskell.org/ghcup/$(uname -m)-linux-ghcup"+        chmod +x "$RUNNER_TEMP"/.ghcup/bin/ghcup+        export GHCUP_INSTALL_BASE_PREFIX="$RUNNER_TEMP" PATH="$RUNNER_TEMP/.ghcup/bin:$PATH"+        echo "GHCUP_INSTALL_BASE_PREFIX=$RUNNER_TEMP" >> "$GITHUB_ENV"+        echo "$RUNNER_TEMP/.ghcup/bin" >> "$GITHUB_PATH"+        versions=$(ghcup -s vanilla list -t ghc -r)+        if grep -qF -e 'ghc ${{ matrix.ghc }} ' -e 'ghc ${{ matrix.ghc }}.' <<< "$versions"; then+          channel=vanilla+        else+          echo 'The vanilla channel of GHCup has no GHC ${{ matrix.ghc }}, so the step uses the prerelease channel.'+          channel=prereleases+        fi+        ghcup -s "$channel" install ghc '${{ matrix.ghc }}' --set+        ghcup -s vanilla install cabal 3.18.1.0 --set+        cabal update+        echo "ghc-version=$(ghc --numeric-version)" >> "$GITHUB_OUTPUT"+        echo "cabal-version=$(cabal --numeric-version)" >> "$GITHUB_OUTPUT"+        echo "cabal-store=$(cabal path -z --store-dir)" >> "$GITHUB_OUTPUT"++    - name: Show the versions+      id: versions+      run: |+        ghc --version+        cabal --version+        echo "GHC ${{ steps.setup.outputs.ghc-version }}, cabal ${{ steps.setup.outputs.cabal-version }}, image $ImageOS $ImageVersion" >> "$GITHUB_STEP_SUMMARY"+        echo "image=$ImageOS" >> "$GITHUB_OUTPUT"++    - name: Show the Postgres version+      run: psql --version++    - name: Unpack the source tarballs+      run: |+        shopt -s extglob+        cabal sdist all --output-directory="$RUNNER_TEMP"/haskell-gha-sdist+        mkdir "$RUNNER_TEMP"/haskell-gha+        for f in cabal.project cabal.project.freeze cabal.project.local; do+          if [ -f "$f" ]; then cp "$f" "$RUNNER_TEMP"/haskell-gha; fi+        done+        tar -xzf "$RUNNER_TEMP"/haskell-gha-sdist/config-+([0-9.]).tar.gz --strip-components=1 -C "$RUNNER_TEMP"/haskell-gha++    - name: Configure the project+      working-directory: ${{ runner.temp }}/haskell-gha+      run: |+        if [ -f cabal.project.local ]; then+          echo '::error::The repository contains cabal.project.local, which holds the settings of one developer. Move the settings to cabal.project or to the key cabal-project-local of the configuration of haskell-gha, and remove the file from the repository.'+          exit 1+        fi+        cat >> cabal.project.local <<'EOF'+        jobs: 2++        program-options+          ghc-options: -Werror -Wno-unused-imports++        package config+          flags: +postgres++        constraints: postgresql-libpq >= 0.10+        EOF++    - name: Prefer the oldest dependencies+      if: matrix.dependencies == 'oldest'+      working-directory: ${{ runner.temp }}/haskell-gha+      run: |+        echo 'prefer-oldest: True' >> cabal.project.local++    - name: Enable the GHC job semaphore or parallel module builds+      working-directory: ${{ runner.temp }}/haskell-gha+      run: |+        if ghc --info | grep -F '("Semaphore version","2")' > /dev/null; then+        echo 'GHC and cabal use version 2 of the semaphore protocol, so GHC uses the semaphore.'+        cat >> cabal.project.local <<'EOF'+        semaphore: True+        EOF+        else+        echo 'GHC uses version 1 of the semaphore protocol and cabal version 2, so GHC uses -j2.'+        cat >> cabal.project.local <<'EOF'+        program-options+          ghc-options: -j2+        EOF+        fi++    - name: Make the build plan+      id: plan+      working-directory: ${{ runner.temp }}/haskell-gha+      run: |+        cabal build all --dry-run+        echo "hash=$(sha256sum dist-newstyle/cache/plan.json | cut -d ' ' -f 1)" >> "$GITHUB_OUTPUT"++    - uses: runs-on/cache/restore@v4+      id: cache+      with:+        path: ${{ steps.setup.outputs.cabal-store }}+        key: haskell-gha.yaml-v1-${{ runner.os }}-${{ runner.arch }}-${{ steps.versions.outputs.image }}-ghc-${{ steps.setup.outputs.ghc-version }}-${{ matrix.dependencies }}-${{ steps.plan.outputs.hash }}+        restore-keys: haskell-gha.yaml-v1-${{ runner.os }}-${{ runner.arch }}-${{ steps.versions.outputs.image }}-ghc-${{ steps.setup.outputs.ghc-version }}-${{ matrix.dependencies }}-++    - name: Build the dependencies+      working-directory: ${{ runner.temp }}/haskell-gha+      run: |+        cabal build all --only-dependencies++    - uses: runs-on/cache/save@v4+      if: steps.cache.outputs.cache-hit != 'true'+      with:+        path: ${{ steps.setup.outputs.cabal-store }}+        key: ${{ steps.cache.outputs.cache-primary-key }}++    - name: Build+      working-directory: ${{ runner.temp }}/haskell-gha+      run: |+        cabal build all++    # A check that the build made the programs.+    - name: Show the executables+      run: cabal list-bin all++    - name: Check the packages+      working-directory: ${{ runner.temp }}/haskell-gha+      run: |+        failed=0+        check() {+          echo "Checking the package $1"+          (cd "$2" && cabal check) || { echo "::error::cabal check failed for the package $1"; failed=1; }+        }+        check config .+        exit "$failed"++    - name: Build the documentation+      working-directory: ${{ runner.temp }}/haskell-gha+      run: |+        cabal haddock all --disable-documentation --haddock-for-hackage
+ tests/golden/config/haskell-gha.conf.yaml view
@@ -0,0 +1,73 @@+name: Postgres CI+cabal-version: 3.18.1.0+runs-on: ubuntu-24.04+timeout-minutes: 90+branches: [master, 'release/**']+submodules: recursive+# The oldest and the newest supported Postgres.+matrix:+  postgres: ['15', '18']+  exclude:+    - ghc: '9.10'+      postgres: '15'+# The workflow does not copy this key, so it drops this comment.+apt: [libpq-dev, postgresql-client]+# The services of each build job.+services:+  # The database for the tests.+  postgres:+    image: postgres:${{ matrix.postgres }}+    env:+      POSTGRES_PASSWORD: postgres # Only for CI.+    ports: ['5432:5432']+    # The runner starts the steps when the database accepts connections.+    options: >-+      --health-cmd pg_isready+      --health-interval 5s+      --health-retries 10+# The test reporter writes check runs.+permissions:+  contents: read+  # For the annotations of the test results.+  checks: write+# The steps for Postgres.+hooks:+  after-setup:+    - name: Show the Postgres version+      run: psql --version+    # Postgres is ready for the build.+  after-build:+    # A check that the build made the programs.+    - name: Show the executables+      run: cabal list-bin all+    # The package checks come next.+ghc-options: -Werror -Wno-unused-imports+cabal-project-local: |+  package config+    flags: +postgres++  constraints: postgresql-libpq >= 0.10+cabal-jobs: 2+tests: false+benchmarks: false+dependencies: both+fourmolu:+  version: '0.19.0.1'+  patterns:+    - 'src/**/*.hs'+    - '!src/Generated.hs'+  runs-on:+    group: small+    labels: [self-hosted, linux]+hlint:+  version: '3.8'+  fail-on: error+  paths: [src, test]+  # HLint needs no large runner.+  runs-on: ubuntu-slim+actions:+  checkout: v6+  cache: runs-on/cache@v4+  run-fourmolu: v12+  hlint-setup: v2+  hlint-run: v2
+ tests/golden/container/container.cabal view
@@ -0,0 +1,9 @@+cabal-version: 3.0+name:               container+version: 0+tested-with: GHC ^>= { 9.4, 9.12 }+library+  exposed-modules: M+test-suite test+  type: exitcode-stdio-1.0+  main-is: Main.hs
+ tests/golden/container/expected.yaml view
@@ -0,0 +1,196 @@+# Do not edit this file, it was generated by the following command:+#   haskell-gha --generate --config haskell-gha.conf.yaml+#+# To regenerate it, run from the root of the repository:+#   haskell-gha+#+# For more information, see https://github.com/arybczak/haskell-gha++name: CI++on:+  push:+    branches:+    - master+    - main+  pull_request:+  merge_group:+  workflow_dispatch:++permissions:+  contents: read++concurrency:+  group: ${{ github.workflow_ref }}+  cancel-in-progress: true++defaults:+  run:+    shell: bash++jobs:+  build:+    name: GHC ${{ matrix.ghc }}+    runs-on: ubuntu-26.04+    container: buildpack-deps:26.04+    timeout-minutes: 60+    services:+      postgres:+        image: postgres:18+        env:+          POSTGRES_PASSWORD: postgres+    strategy:+      fail-fast: false+      matrix:+        ghc:+        - '9.4'+        - '9.12'+    steps:+    - uses: actions/checkout@v7+      with:+        persist-credentials: false++    - name: Install the system packages+      run: |+        apt-get update+        DEBIAN_FRONTEND=noninteractive apt-get install -y --no-install-recommends libpq-dev++    - name: Install the gold linker+      if: contains(fromJSON('["9.4"]'), matrix.ghc)+      run: |+        apt-get update+        DEBIAN_FRONTEND=noninteractive apt-get install -y --no-install-recommends binutils-gold++    - name: Install GHC and cabal+      id: setup+      run: |+        mkdir -p "$RUNNER_TEMP"/.ghcup/bin+        curl -fsSL -o "$RUNNER_TEMP"/.ghcup/bin/ghcup "https://downloads.haskell.org/ghcup/$(uname -m)-linux-ghcup"+        chmod +x "$RUNNER_TEMP"/.ghcup/bin/ghcup+        export GHCUP_INSTALL_BASE_PREFIX="$RUNNER_TEMP" PATH="$RUNNER_TEMP/.ghcup/bin:$PATH"+        echo "GHCUP_INSTALL_BASE_PREFIX=$RUNNER_TEMP" >> "$GITHUB_ENV"+        echo "$RUNNER_TEMP/.ghcup/bin" >> "$GITHUB_PATH"+        versions=$(ghcup -s vanilla list -t ghc -r)+        if grep -qF -e 'ghc ${{ matrix.ghc }} ' -e 'ghc ${{ matrix.ghc }}.' <<< "$versions"; then+          channel=vanilla+        else+          echo 'The vanilla channel of GHCup has no GHC ${{ matrix.ghc }}, so the step uses the prerelease channel.'+          channel=prereleases+        fi+        ghcup -s "$channel" install ghc '${{ matrix.ghc }}' --set+        ghcup -s vanilla install cabal 3.16.1.0 --set+        cabal update+        echo "ghc-version=$(ghc --numeric-version)" >> "$GITHUB_OUTPUT"+        echo "cabal-version=$(cabal --numeric-version)" >> "$GITHUB_OUTPUT"+        echo "cabal-store=$(cabal path -z --store-dir)" >> "$GITHUB_OUTPUT"++    - name: Show the versions+      id: versions+      run: |+        ghc --version+        cabal --version+        echo "GHC ${{ steps.setup.outputs.ghc-version }}, cabal ${{ steps.setup.outputs.cabal-version }}, image buildpack-deps:26.04" >> "$GITHUB_STEP_SUMMARY"+        echo "image=buildpack-deps:26.04" >> "$GITHUB_OUTPUT"++    - name: Unpack the source tarballs+      run: |+        shopt -s extglob+        cabal sdist all --output-directory="$RUNNER_TEMP"/haskell-gha-sdist+        mkdir "$RUNNER_TEMP"/haskell-gha+        for f in cabal.project cabal.project.freeze cabal.project.local; do+          if [ -f "$f" ]; then cp "$f" "$RUNNER_TEMP"/haskell-gha; fi+        done+        tar -xzf "$RUNNER_TEMP"/haskell-gha-sdist/container-+([0-9.]).tar.gz --strip-components=1 -C "$RUNNER_TEMP"/haskell-gha++    - name: Configure the project+      working-directory: ${{ runner.temp }}/haskell-gha+      run: |+        if [ -f cabal.project.local ]; then+          echo '::error::The repository contains cabal.project.local, which holds the settings of one developer. Move the settings to cabal.project or to the key cabal-project-local of the configuration of haskell-gha, and remove the file from the repository.'+          exit 1+        fi+        cat >> cabal.project.local <<'EOF'+        jobs: 4+        tests: True+        benchmarks: True++        program-options+          ghc-options: -Werror+        EOF++    - name: Enable parallel module builds for the local packages+      if: contains(fromJSON('["9.4"]'), matrix.ghc)+      working-directory: ${{ runner.temp }}/haskell-gha+      run: |+        cat >> cabal.project.local <<'EOF'+        program-options+          ghc-options: -j4+        EOF++    - name: Enable the GHC job semaphore or parallel module builds+      if: contains(fromJSON('["9.12"]'), matrix.ghc)+      working-directory: ${{ runner.temp }}/haskell-gha+      run: |+        if ghc --info | grep -F '("Semaphore version","2")' > /dev/null; then+        echo 'GHC uses version 2 of the semaphore protocol and cabal version 1, so GHC uses -j4.'+        cat >> cabal.project.local <<'EOF'+        program-options+          ghc-options: -j4+        EOF+        else+        echo 'GHC and cabal use version 1 of the semaphore protocol, so GHC uses the semaphore.'+        cat >> cabal.project.local <<'EOF'+        semaphore: True+        EOF+        fi++    - name: Make the build plan+      id: plan+      working-directory: ${{ runner.temp }}/haskell-gha+      run: |+        cabal build all --dry-run+        echo "hash=$(sha256sum dist-newstyle/cache/plan.json | cut -d ' ' -f 1)" >> "$GITHUB_OUTPUT"++    - uses: actions/cache/restore@v6+      id: cache+      with:+        path: ${{ steps.setup.outputs.cabal-store }}+        key: haskell-gha.yaml-v1-${{ runner.os }}-${{ runner.arch }}-${{ steps.versions.outputs.image }}-ghc-${{ steps.setup.outputs.ghc-version }}-newest-${{ steps.plan.outputs.hash }}+        restore-keys: haskell-gha.yaml-v1-${{ runner.os }}-${{ runner.arch }}-${{ steps.versions.outputs.image }}-ghc-${{ steps.setup.outputs.ghc-version }}-newest-++    - name: Build the dependencies+      working-directory: ${{ runner.temp }}/haskell-gha+      run: |+        cabal build all --only-dependencies++    - uses: actions/cache/save@v6+      if: steps.cache.outputs.cache-hit != 'true'+      with:+        path: ${{ steps.setup.outputs.cabal-store }}+        key: ${{ steps.cache.outputs.cache-primary-key }}++    - name: Build+      working-directory: ${{ runner.temp }}/haskell-gha+      run: |+        cabal build all++    - name: Run the tests+      working-directory: ${{ runner.temp }}/haskell-gha+      run: |+        cabal test all --test-show-details=direct++    - name: Check the packages+      working-directory: ${{ runner.temp }}/haskell-gha+      run: |+        failed=0+        check() {+          echo "Checking the package $1"+          (cd "$2" && cabal check) || { echo "::error::cabal check failed for the package $1"; failed=1; }+        }+        check container .+        exit "$failed"++    - name: Build the documentation+      working-directory: ${{ runner.temp }}/haskell-gha+      run: |+        cabal haddock all --disable-documentation --haddock-for-hackage
+ tests/golden/container/haskell-gha.conf.yaml view
@@ -0,0 +1,7 @@+container: buildpack-deps:26.04+apt: [libpq-dev]+services:+  postgres:+    image: postgres:18+    env:+      POSTGRES_PASSWORD: postgres
+ tests/golden/doctest/a/a.cabal view
@@ -0,0 +1,16 @@+cabal-version: 3.0+name:          a+version:       0+tested-with:   GHC == 9.6.7 || ^>= { 9.10, 9.12 }++library+  hs-source-dirs:     src+  exposed-modules:    A+  default-language:   GHC2021+  default-extensions: LambdaCase+                      OverloadedStrings++library internal+  hs-source-dirs:   internal+  exposed-modules:  A.Internal+  default-language: Haskell2010
+ tests/golden/doctest/b/B.hs view
@@ -0,0 +1,1 @@+module B where
+ tests/golden/doctest/b/b.cabal view
@@ -0,0 +1,7 @@+cabal-version: 3.0+name:          b+version:       0+tested-with:   GHC == 9.6.7 || ^>= { 9.10, 9.12 }++library+  exposed-modules: B
+ tests/golden/doctest/c/c.cabal view
@@ -0,0 +1,7 @@+cabal-version: 3.0+name:          c+version:       0+tested-with:   GHC == 9.6.7 || ^>= { 9.10, 9.12 }++library+  exposed-modules: C
+ tests/golden/doctest/cabal.project view
@@ -0,0 +1,1 @@+packages: a b c
+ tests/golden/doctest/expected.yaml view
@@ -0,0 +1,227 @@+# Do not edit this file, it was generated by the following command:+#   haskell-gha --generate --config haskell-gha.conf.yaml+#+# To regenerate it, run from the root of the repository:+#   haskell-gha+#+# For more information, see https://github.com/arybczak/haskell-gha++name: CI++on:+  push:+    branches:+    - master+    - main+  pull_request:+  merge_group:+  workflow_dispatch:++permissions:+  contents: read++concurrency:+  group: ${{ github.workflow_ref }}+  cancel-in-progress: true++defaults:+  run:+    shell: bash++jobs:+  build:+    name: GHC ${{ matrix.ghc }}+    runs-on: ubuntu-26.04+    timeout-minutes: 60+    strategy:+      fail-fast: false+      matrix:+        ghc:+        - '9.6.7'+        - '9.10'+        - '9.12'+    steps:+    - uses: actions/checkout@v7+      with:+        persist-credentials: false++    - name: Install GHC and cabal+      id: setup+      run: |+        mkdir -p "$RUNNER_TEMP"/.ghcup/bin+        curl -fsSL -o "$RUNNER_TEMP"/.ghcup/bin/ghcup "https://downloads.haskell.org/ghcup/$(uname -m)-linux-ghcup"+        chmod +x "$RUNNER_TEMP"/.ghcup/bin/ghcup+        export GHCUP_INSTALL_BASE_PREFIX="$RUNNER_TEMP" PATH="$RUNNER_TEMP/.ghcup/bin:$PATH"+        echo "GHCUP_INSTALL_BASE_PREFIX=$RUNNER_TEMP" >> "$GITHUB_ENV"+        echo "$RUNNER_TEMP/.ghcup/bin" >> "$GITHUB_PATH"+        versions=$(ghcup -s vanilla list -t ghc -r)+        if grep -qF -e 'ghc ${{ matrix.ghc }} ' -e 'ghc ${{ matrix.ghc }}.' <<< "$versions"; then+          channel=vanilla+        else+          echo 'The vanilla channel of GHCup has no GHC ${{ matrix.ghc }}, so the step uses the prerelease channel.'+          channel=prereleases+        fi+        ghcup -s "$channel" install ghc '${{ matrix.ghc }}' --set+        ghcup -s vanilla install cabal 3.16.1.0 --set+        cabal update+        echo "ghc-version=$(ghc --numeric-version)" >> "$GITHUB_OUTPUT"+        echo "cabal-version=$(cabal --numeric-version)" >> "$GITHUB_OUTPUT"+        echo "cabal-store=$(cabal path -z --store-dir)" >> "$GITHUB_OUTPUT"++    - name: Show the versions+      id: versions+      run: |+        ghc --version+        cabal --version+        echo "GHC ${{ steps.setup.outputs.ghc-version }}, cabal ${{ steps.setup.outputs.cabal-version }}, image $ImageOS $ImageVersion" >> "$GITHUB_STEP_SUMMARY"+        echo "image=$ImageOS" >> "$GITHUB_OUTPUT"++    - name: Unpack the source tarballs+      run: |+        shopt -s extglob+        cabal sdist all --output-directory="$RUNNER_TEMP"/haskell-gha-sdist+        mkdir "$RUNNER_TEMP"/haskell-gha+        for f in cabal.project cabal.project.freeze cabal.project.local; do+          if [ -f "$f" ]; then cp "$f" "$RUNNER_TEMP"/haskell-gha; fi+        done+        mkdir -p "$RUNNER_TEMP"/haskell-gha/a+        tar -xzf "$RUNNER_TEMP"/haskell-gha-sdist/a-+([0-9.]).tar.gz --strip-components=1 -C "$RUNNER_TEMP"/haskell-gha/a+        mkdir -p "$RUNNER_TEMP"/haskell-gha/b+        tar -xzf "$RUNNER_TEMP"/haskell-gha-sdist/b-+([0-9.]).tar.gz --strip-components=1 -C "$RUNNER_TEMP"/haskell-gha/b+        mkdir -p "$RUNNER_TEMP"/haskell-gha/c+        tar -xzf "$RUNNER_TEMP"/haskell-gha-sdist/c-+([0-9.]).tar.gz --strip-components=1 -C "$RUNNER_TEMP"/haskell-gha/c++    - name: Configure the project+      working-directory: ${{ runner.temp }}/haskell-gha+      run: |+        if [ -f cabal.project.local ]; then+          echo '::error::The repository contains cabal.project.local, which holds the settings of one developer. Move the settings to cabal.project or to the key cabal-project-local of the configuration of haskell-gha, and remove the file from the repository.'+          exit 1+        fi+        cat >> cabal.project.local <<'EOF'+        jobs: 4+        tests: True+        benchmarks: True+        write-ghc-environment-files: always++        program-options+          ghc-options: -Werror+        EOF++    - name: Enable parallel module builds for the local packages+      if: contains(fromJSON('["9.6.7"]'), matrix.ghc)+      working-directory: ${{ runner.temp }}/haskell-gha+      run: |+        cat >> cabal.project.local <<'EOF'+        program-options+          ghc-options: -j4+        EOF++    - name: Enable the GHC job semaphore or parallel module builds+      if: contains(fromJSON('["9.10","9.12"]'), matrix.ghc)+      working-directory: ${{ runner.temp }}/haskell-gha+      run: |+        if ghc --info | grep -F '("Semaphore version","2")' > /dev/null; then+        echo 'GHC uses version 2 of the semaphore protocol and cabal version 1, so GHC uses -j4.'+        cat >> cabal.project.local <<'EOF'+        program-options+          ghc-options: -j4+        EOF+        else+        echo 'GHC and cabal use version 1 of the semaphore protocol, so GHC uses the semaphore.'+        cat >> cabal.project.local <<'EOF'+        semaphore: True+        EOF+        fi++    - name: Make the build plan+      id: plan+      working-directory: ${{ runner.temp }}/haskell-gha+      run: |+        cabal build all --dry-run+        echo "hash=$(sha256sum dist-newstyle/cache/plan.json | cut -d ' ' -f 1)" >> "$GITHUB_OUTPUT"++    - uses: actions/cache/restore@v6+      id: cache+      with:+        path: ${{ steps.setup.outputs.cabal-store }}+        key: haskell-gha.yaml-v1-${{ runner.os }}-${{ runner.arch }}-${{ steps.versions.outputs.image }}-ghc-${{ steps.setup.outputs.ghc-version }}-newest-${{ steps.plan.outputs.hash }}+        restore-keys: haskell-gha.yaml-v1-${{ runner.os }}-${{ runner.arch }}-${{ steps.versions.outputs.image }}-ghc-${{ steps.setup.outputs.ghc-version }}-newest-++    - name: Build the dependencies+      working-directory: ${{ runner.temp }}/haskell-gha+      run: |+        cabal build all --only-dependencies++    - uses: actions/cache/save@v6+      if: steps.cache.outputs.cache-hit != 'true'+      with:+        path: ${{ steps.setup.outputs.cabal-store }}+        key: ${{ steps.cache.outputs.cache-primary-key }}++    - name: Find the doctest version+      id: doctest+      if: contains(fromJSON('["9.10","9.12"]'), matrix.ghc)+      run: |+        version=$(cabal --store-dir="$RUNNER_TEMP"/doctest-store install doctest --ignore-project --dry-run --constraint='doctest >=0.24' | sed -n 's/^ - doctest-\([0-9.]*\) (exe:doctest).*/\1/p')+        if [ -z "$version" ]; then+          echo 'The dry run of cabal install shows no doctest version.' >&2+          exit 1+        fi+        echo "version=$version" >> "$GITHUB_OUTPUT"++    - uses: actions/cache/restore@v6+      id: doctest-cache+      if: contains(fromJSON('["9.10","9.12"]'), matrix.ghc)+      with:+        path: ~/.local/bin/doctest+        key: haskell-gha-v1-${{ runner.os }}-${{ runner.arch }}-${{ steps.versions.outputs.image }}-doctest-${{ steps.doctest.outputs.version }}-ghc-${{ steps.setup.outputs.ghc-version }}++    - name: Install doctest+      if: contains(fromJSON('["9.10","9.12"]'), matrix.ghc) && steps.doctest-cache.outputs.cache-hit != 'true'+      run: |+        cabal install doctest --ignore-project --install-method=copy --installdir="$HOME/.local/bin" --overwrite-policy=always --constraint='doctest ==${{ steps.doctest.outputs.version }}'++    - uses: actions/cache/save@v6+      if: contains(fromJSON('["9.10","9.12"]'), matrix.ghc) && steps.doctest-cache.outputs.cache-hit != 'true'+      with:+        path: ~/.local/bin/doctest+        key: ${{ steps.doctest-cache.outputs.cache-primary-key }}++    - name: Build+      working-directory: ${{ runner.temp }}/haskell-gha+      run: |+        cabal build all++    - name: Run doctest for a+      if: contains(fromJSON('["9.10","9.12"]'), matrix.ghc)+      working-directory: ${{ runner.temp }}/haskell-gha+      run: |+        cd a+        "$HOME"/.local/bin/doctest --fast -XGHC2021 -XLambdaCase -XOverloadedStrings src+        "$HOME"/.local/bin/doctest --fast -XHaskell2010 internal++    - name: Run doctest for b+      if: contains(fromJSON('["9.10","9.12"]'), matrix.ghc)+      working-directory: ${{ runner.temp }}/haskell-gha+      run: |+        cd b+        "$HOME"/.local/bin/doctest --fast B.hs++    - name: Check the packages+      working-directory: ${{ runner.temp }}/haskell-gha+      run: |+        failed=0+        check() {+          echo "Checking the package $1"+          (cd "$2" && cabal check) || { echo "::error::cabal check failed for the package $1"; failed=1; }+        }+        check a a+        check b b+        check c c+        exit "$failed"++    - name: Build the documentation+      working-directory: ${{ runner.temp }}/haskell-gha+      run: |+        cabal haddock all --disable-documentation --haddock-for-hackage
+ tests/golden/doctest/haskell-gha.conf.yaml view
@@ -0,0 +1,5 @@+doctest:+  ghc: '>=9.8'+  version: '>=0.24'+  skip-packages: [c]+  options: [--fast]
+ tests/golden/multi/cabal.project view
@@ -0,0 +1,4 @@+packages: core++if impl(ghc >= 9.10)+  packages: new
+ tests/golden/multi/core/core.cabal view
@@ -0,0 +1,7 @@+cabal-version: 3.0+name:          core+version:       0+tested-with:   GHC == 9.6.7 || ^>= { 9.10, 9.12 }++library+  exposed-modules: Core
+ tests/golden/multi/expected.yaml view
@@ -0,0 +1,211 @@+# Do not edit this file, it was generated by the following command:+#   haskell-gha --generate+#+# To regenerate it, run from the root of the repository:+#   haskell-gha+#+# For more information, see https://github.com/arybczak/haskell-gha++name: CI++on:+  push:+    branches:+    - master+    - main+  pull_request:+  merge_group:+  workflow_dispatch:++permissions:+  contents: read++concurrency:+  group: ${{ github.workflow_ref }}+  cancel-in-progress: true++defaults:+  run:+    shell: bash++jobs:+  build:+    name: GHC ${{ matrix.ghc }}+    runs-on: ubuntu-26.04+    timeout-minutes: 60+    strategy:+      fail-fast: false+      matrix:+        ghc:+        - '9.6.7'+        - '9.10'+        - '9.12'+    steps:+    - uses: actions/checkout@v7+      with:+        persist-credentials: false++    - name: Install GHC and cabal+      id: setup+      run: |+        mkdir -p "$RUNNER_TEMP"/.ghcup/bin+        curl -fsSL -o "$RUNNER_TEMP"/.ghcup/bin/ghcup "https://downloads.haskell.org/ghcup/$(uname -m)-linux-ghcup"+        chmod +x "$RUNNER_TEMP"/.ghcup/bin/ghcup+        export GHCUP_INSTALL_BASE_PREFIX="$RUNNER_TEMP" PATH="$RUNNER_TEMP/.ghcup/bin:$PATH"+        echo "GHCUP_INSTALL_BASE_PREFIX=$RUNNER_TEMP" >> "$GITHUB_ENV"+        echo "$RUNNER_TEMP/.ghcup/bin" >> "$GITHUB_PATH"+        versions=$(ghcup -s vanilla list -t ghc -r)+        if grep -qF -e 'ghc ${{ matrix.ghc }} ' -e 'ghc ${{ matrix.ghc }}.' <<< "$versions"; then+          channel=vanilla+        else+          echo 'The vanilla channel of GHCup has no GHC ${{ matrix.ghc }}, so the step uses the prerelease channel.'+          channel=prereleases+        fi+        ghcup -s "$channel" install ghc '${{ matrix.ghc }}' --set+        ghcup -s vanilla install cabal 3.16.1.0 --set+        cabal update+        echo "ghc-version=$(ghc --numeric-version)" >> "$GITHUB_OUTPUT"+        echo "cabal-version=$(cabal --numeric-version)" >> "$GITHUB_OUTPUT"+        echo "cabal-store=$(cabal path -z --store-dir)" >> "$GITHUB_OUTPUT"++    - name: Show the versions+      id: versions+      run: |+        ghc --version+        cabal --version+        echo "GHC ${{ steps.setup.outputs.ghc-version }}, cabal ${{ steps.setup.outputs.cabal-version }}, image $ImageOS $ImageVersion" >> "$GITHUB_STEP_SUMMARY"+        echo "image=$ImageOS" >> "$GITHUB_OUTPUT"++    - name: Unpack the source tarballs+      if: contains(fromJSON('["9.6.7"]'), matrix.ghc)+      run: |+        shopt -s extglob+        cabal sdist all --output-directory="$RUNNER_TEMP"/haskell-gha-sdist+        mkdir "$RUNNER_TEMP"/haskell-gha+        for f in cabal.project cabal.project.freeze cabal.project.local; do+          if [ -f "$f" ]; then cp "$f" "$RUNNER_TEMP"/haskell-gha; fi+        done+        mkdir -p "$RUNNER_TEMP"/haskell-gha/core+        tar -xzf "$RUNNER_TEMP"/haskell-gha-sdist/core-+([0-9.]).tar.gz --strip-components=1 -C "$RUNNER_TEMP"/haskell-gha/core++    - name: Unpack the source tarballs+      if: contains(fromJSON('["9.10","9.12"]'), matrix.ghc)+      run: |+        shopt -s extglob+        cabal sdist all --output-directory="$RUNNER_TEMP"/haskell-gha-sdist+        mkdir "$RUNNER_TEMP"/haskell-gha+        for f in cabal.project cabal.project.freeze cabal.project.local; do+          if [ -f "$f" ]; then cp "$f" "$RUNNER_TEMP"/haskell-gha; fi+        done+        mkdir -p "$RUNNER_TEMP"/haskell-gha/core+        tar -xzf "$RUNNER_TEMP"/haskell-gha-sdist/core-+([0-9.]).tar.gz --strip-components=1 -C "$RUNNER_TEMP"/haskell-gha/core+        mkdir -p "$RUNNER_TEMP"/haskell-gha/new+        tar -xzf "$RUNNER_TEMP"/haskell-gha-sdist/new-+([0-9.]).tar.gz --strip-components=1 -C "$RUNNER_TEMP"/haskell-gha/new++    - name: Configure the project+      working-directory: ${{ runner.temp }}/haskell-gha+      run: |+        if [ -f cabal.project.local ]; then+          echo '::error::The repository contains cabal.project.local, which holds the settings of one developer. Move the settings to cabal.project or to the key cabal-project-local of the configuration of haskell-gha, and remove the file from the repository.'+          exit 1+        fi+        cat >> cabal.project.local <<'EOF'+        jobs: 4+        tests: True+        benchmarks: True++        program-options+          ghc-options: -Werror+        EOF++    - name: Enable parallel module builds for the local packages+      if: contains(fromJSON('["9.6.7"]'), matrix.ghc)+      working-directory: ${{ runner.temp }}/haskell-gha+      run: |+        cat >> cabal.project.local <<'EOF'+        program-options+          ghc-options: -j4+        EOF++    - name: Enable the GHC job semaphore or parallel module builds+      if: contains(fromJSON('["9.10","9.12"]'), matrix.ghc)+      working-directory: ${{ runner.temp }}/haskell-gha+      run: |+        if ghc --info | grep -F '("Semaphore version","2")' > /dev/null; then+        echo 'GHC uses version 2 of the semaphore protocol and cabal version 1, so GHC uses -j4.'+        cat >> cabal.project.local <<'EOF'+        program-options+          ghc-options: -j4+        EOF+        else+        echo 'GHC and cabal use version 1 of the semaphore protocol, so GHC uses the semaphore.'+        cat >> cabal.project.local <<'EOF'+        semaphore: True+        EOF+        fi++    - name: Make the build plan+      id: plan+      working-directory: ${{ runner.temp }}/haskell-gha+      run: |+        cabal build all --dry-run+        echo "hash=$(sha256sum dist-newstyle/cache/plan.json | cut -d ' ' -f 1)" >> "$GITHUB_OUTPUT"++    - uses: actions/cache/restore@v6+      id: cache+      with:+        path: ${{ steps.setup.outputs.cabal-store }}+        key: haskell-gha.yaml-v1-${{ runner.os }}-${{ runner.arch }}-${{ steps.versions.outputs.image }}-ghc-${{ steps.setup.outputs.ghc-version }}-newest-${{ steps.plan.outputs.hash }}+        restore-keys: haskell-gha.yaml-v1-${{ runner.os }}-${{ runner.arch }}-${{ steps.versions.outputs.image }}-ghc-${{ steps.setup.outputs.ghc-version }}-newest-++    - name: Build the dependencies+      working-directory: ${{ runner.temp }}/haskell-gha+      run: |+        cabal build all --only-dependencies++    - uses: actions/cache/save@v6+      if: steps.cache.outputs.cache-hit != 'true'+      with:+        path: ${{ steps.setup.outputs.cabal-store }}+        key: ${{ steps.cache.outputs.cache-primary-key }}++    - name: Build+      working-directory: ${{ runner.temp }}/haskell-gha+      run: |+        cabal build all++    - name: Run the tests+      if: contains(fromJSON('["9.10","9.12"]'), matrix.ghc)+      working-directory: ${{ runner.temp }}/haskell-gha+      run: |+        cabal test all --test-show-details=direct++    - name: Check the packages+      if: contains(fromJSON('["9.6.7"]'), matrix.ghc)+      working-directory: ${{ runner.temp }}/haskell-gha+      run: |+        failed=0+        check() {+          echo "Checking the package $1"+          (cd "$2" && cabal check) || { echo "::error::cabal check failed for the package $1"; failed=1; }+        }+        check core core+        exit "$failed"++    - name: Check the packages+      if: contains(fromJSON('["9.10","9.12"]'), matrix.ghc)+      working-directory: ${{ runner.temp }}/haskell-gha+      run: |+        failed=0+        check() {+          echo "Checking the package $1"+          (cd "$2" && cabal check) || { echo "::error::cabal check failed for the package $1"; failed=1; }+        }+        check core core+        check new new+        exit "$failed"++    - name: Build the documentation+      working-directory: ${{ runner.temp }}/haskell-gha+      run: |+        cabal haddock all --disable-documentation --haddock-for-hackage
+ tests/golden/multi/new/new.cabal view
@@ -0,0 +1,11 @@+cabal-version: 3.0+name:          new+version:       0+tested-with:   GHC ^>= { 9.10, 9.12 }++library+  exposed-modules: New++test-suite test+  type:    exitcode-stdio-1.0+  main-is: Main.hs
+ tests/golden/old-ghc/expected.yaml view
@@ -0,0 +1,168 @@+# Do not edit this file, it was generated by the following command:+#   haskell-gha --generate+#+# To regenerate it, run from the root of the repository:+#   haskell-gha+#+# For more information, see https://github.com/arybczak/haskell-gha++name: CI++on:+  push:+    branches:+    - master+    - main+  pull_request:+  merge_group:+  workflow_dispatch:++permissions:+  contents: read++concurrency:+  group: ${{ github.workflow_ref }}+  cancel-in-progress: true++defaults:+  run:+    shell: bash++jobs:+  build:+    name: GHC ${{ matrix.ghc }}+    runs-on: ubuntu-26.04+    timeout-minutes: 60+    strategy:+      fail-fast: false+      matrix:+        ghc:+        - '9.2.8'+        - '9.4.8'+        - '9.6.7'+    steps:+    - uses: actions/checkout@v7+      with:+        persist-credentials: false++    - name: Install the gold linker+      if: contains(fromJSON('["9.2.8","9.4.8"]'), matrix.ghc)+      run: |+        sudo apt-get update+        sudo DEBIAN_FRONTEND=noninteractive apt-get install -y --no-install-recommends binutils-gold++    - name: Install GHC and cabal+      id: setup+      run: |+        mkdir -p "$RUNNER_TEMP"/.ghcup/bin+        curl -fsSL -o "$RUNNER_TEMP"/.ghcup/bin/ghcup "https://downloads.haskell.org/ghcup/$(uname -m)-linux-ghcup"+        chmod +x "$RUNNER_TEMP"/.ghcup/bin/ghcup+        export GHCUP_INSTALL_BASE_PREFIX="$RUNNER_TEMP" PATH="$RUNNER_TEMP/.ghcup/bin:$PATH"+        echo "GHCUP_INSTALL_BASE_PREFIX=$RUNNER_TEMP" >> "$GITHUB_ENV"+        echo "$RUNNER_TEMP/.ghcup/bin" >> "$GITHUB_PATH"+        versions=$(ghcup -s vanilla list -t ghc -r)+        if grep -qF -e 'ghc ${{ matrix.ghc }} ' -e 'ghc ${{ matrix.ghc }}.' <<< "$versions"; then+          channel=vanilla+        else+          echo 'The vanilla channel of GHCup has no GHC ${{ matrix.ghc }}, so the step uses the prerelease channel.'+          channel=prereleases+        fi+        ghcup -s "$channel" install ghc '${{ matrix.ghc }}' --set+        ghcup -s vanilla install cabal 3.16.1.0 --set+        cabal update+        echo "ghc-version=$(ghc --numeric-version)" >> "$GITHUB_OUTPUT"+        echo "cabal-version=$(cabal --numeric-version)" >> "$GITHUB_OUTPUT"+        echo "cabal-store=$(cabal path -z --store-dir)" >> "$GITHUB_OUTPUT"++    - name: Show the versions+      id: versions+      run: |+        ghc --version+        cabal --version+        echo "GHC ${{ steps.setup.outputs.ghc-version }}, cabal ${{ steps.setup.outputs.cabal-version }}, image $ImageOS $ImageVersion" >> "$GITHUB_STEP_SUMMARY"+        echo "image=$ImageOS" >> "$GITHUB_OUTPUT"++    - name: Unpack the source tarballs+      run: |+        shopt -s extglob+        cabal sdist all --output-directory="$RUNNER_TEMP"/haskell-gha-sdist+        mkdir "$RUNNER_TEMP"/haskell-gha+        for f in cabal.project cabal.project.freeze cabal.project.local; do+          if [ -f "$f" ]; then cp "$f" "$RUNNER_TEMP"/haskell-gha; fi+        done+        tar -xzf "$RUNNER_TEMP"/haskell-gha-sdist/old-+([0-9.]).tar.gz --strip-components=1 -C "$RUNNER_TEMP"/haskell-gha++    - name: Configure the project+      working-directory: ${{ runner.temp }}/haskell-gha+      run: |+        if [ -f cabal.project.local ]; then+          echo '::error::The repository contains cabal.project.local, which holds the settings of one developer. Move the settings to cabal.project or to the key cabal-project-local of the configuration of haskell-gha, and remove the file from the repository.'+          exit 1+        fi+        cat >> cabal.project.local <<'EOF'+        jobs: 4+        tests: True+        benchmarks: True++        program-options+          ghc-options: -Werror+        EOF++    - name: Enable parallel module builds for the local packages+      working-directory: ${{ runner.temp }}/haskell-gha+      run: |+        cat >> cabal.project.local <<'EOF'+        program-options+          ghc-options: -j4+        EOF++    - name: Make the build plan+      id: plan+      working-directory: ${{ runner.temp }}/haskell-gha+      run: |+        cabal build all --dry-run+        echo "hash=$(sha256sum dist-newstyle/cache/plan.json | cut -d ' ' -f 1)" >> "$GITHUB_OUTPUT"++    - uses: actions/cache/restore@v6+      id: cache+      with:+        path: ${{ steps.setup.outputs.cabal-store }}+        key: haskell-gha.yaml-v1-${{ runner.os }}-${{ runner.arch }}-${{ steps.versions.outputs.image }}-ghc-${{ steps.setup.outputs.ghc-version }}-newest-${{ steps.plan.outputs.hash }}+        restore-keys: haskell-gha.yaml-v1-${{ runner.os }}-${{ runner.arch }}-${{ steps.versions.outputs.image }}-ghc-${{ steps.setup.outputs.ghc-version }}-newest-++    - name: Build the dependencies+      working-directory: ${{ runner.temp }}/haskell-gha+      run: |+        cabal build all --only-dependencies++    - uses: actions/cache/save@v6+      if: steps.cache.outputs.cache-hit != 'true'+      with:+        path: ${{ steps.setup.outputs.cabal-store }}+        key: ${{ steps.cache.outputs.cache-primary-key }}++    - name: Build+      working-directory: ${{ runner.temp }}/haskell-gha+      run: |+        cabal build all++    - name: Run the tests+      working-directory: ${{ runner.temp }}/haskell-gha+      run: |+        cabal test all --test-show-details=direct++    - name: Check the packages+      working-directory: ${{ runner.temp }}/haskell-gha+      run: |+        failed=0+        check() {+          echo "Checking the package $1"+          (cd "$2" && cabal check) || { echo "::error::cabal check failed for the package $1"; failed=1; }+        }+        check old .+        exit "$failed"++    - name: Build the documentation+      working-directory: ${{ runner.temp }}/haskell-gha+      run: |+        cabal haddock all --disable-documentation --haddock-for-hackage
+ tests/golden/old-ghc/old.cabal view
@@ -0,0 +1,11 @@+cabal-version: 3.0+name:          old+version:       0+tested-with:   GHC == { 9.2.8, 9.4.8, 9.6.7 }++library+  exposed-modules: Old++test-suite test+  type:    exitcode-stdio-1.0+  main-is: Main.hs
+ tests/golden/oldest/expected.yaml view
@@ -0,0 +1,185 @@+# Do not edit this file, it was generated by the following command:+#   haskell-gha --generate --config haskell-gha.conf.yaml+#+# To regenerate it, run from the root of the repository:+#   haskell-gha+#+# For more information, see https://github.com/arybczak/haskell-gha++name: CI++on:+  push:+    branches:+    - master+    - main+  pull_request:+  merge_group:+  workflow_dispatch:++permissions:+  contents: read++concurrency:+  group: ${{ github.workflow_ref }}+  cancel-in-progress: true++defaults:+  run:+    shell: bash++jobs:+  build:+    name: GHC ${{ matrix.ghc }}+    runs-on: ubuntu-26.04+    timeout-minutes: 60+    strategy:+      fail-fast: false+      matrix:+        ghc:+        - '9.6.7'+        - '9.10'+        - '9.12'+    steps:+    - uses: actions/checkout@v7+      with:+        persist-credentials: false++    - name: Install GHC and cabal+      id: setup+      run: |+        mkdir -p "$RUNNER_TEMP"/.ghcup/bin+        curl -fsSL -o "$RUNNER_TEMP"/.ghcup/bin/ghcup "https://downloads.haskell.org/ghcup/$(uname -m)-linux-ghcup"+        chmod +x "$RUNNER_TEMP"/.ghcup/bin/ghcup+        export GHCUP_INSTALL_BASE_PREFIX="$RUNNER_TEMP" PATH="$RUNNER_TEMP/.ghcup/bin:$PATH"+        echo "GHCUP_INSTALL_BASE_PREFIX=$RUNNER_TEMP" >> "$GITHUB_ENV"+        echo "$RUNNER_TEMP/.ghcup/bin" >> "$GITHUB_PATH"+        versions=$(ghcup -s vanilla list -t ghc -r)+        if grep -qF -e 'ghc ${{ matrix.ghc }} ' -e 'ghc ${{ matrix.ghc }}.' <<< "$versions"; then+          channel=vanilla+        else+          echo 'The vanilla channel of GHCup has no GHC ${{ matrix.ghc }}, so the step uses the prerelease channel.'+          channel=prereleases+        fi+        ghcup -s "$channel" install ghc '${{ matrix.ghc }}' --set+        ghcup -s vanilla install cabal 3.16.1.0 --set+        cabal update+        echo "ghc-version=$(ghc --numeric-version)" >> "$GITHUB_OUTPUT"+        echo "cabal-version=$(cabal --numeric-version)" >> "$GITHUB_OUTPUT"+        echo "cabal-store=$(cabal path -z --store-dir)" >> "$GITHUB_OUTPUT"++    - name: Show the versions+      id: versions+      run: |+        ghc --version+        cabal --version+        echo "GHC ${{ steps.setup.outputs.ghc-version }}, cabal ${{ steps.setup.outputs.cabal-version }}, image $ImageOS $ImageVersion" >> "$GITHUB_STEP_SUMMARY"+        echo "image=$ImageOS" >> "$GITHUB_OUTPUT"++    - name: Unpack the source tarballs+      run: |+        shopt -s extglob+        cabal sdist all --output-directory="$RUNNER_TEMP"/haskell-gha-sdist+        mkdir "$RUNNER_TEMP"/haskell-gha+        for f in cabal.project cabal.project.freeze cabal.project.local; do+          if [ -f "$f" ]; then cp "$f" "$RUNNER_TEMP"/haskell-gha; fi+        done+        tar -xzf "$RUNNER_TEMP"/haskell-gha-sdist/oldest-+([0-9.]).tar.gz --strip-components=1 -C "$RUNNER_TEMP"/haskell-gha++    - name: Configure the project+      working-directory: ${{ runner.temp }}/haskell-gha+      run: |+        if [ -f cabal.project.local ]; then+          echo '::error::The repository contains cabal.project.local, which holds the settings of one developer. Move the settings to cabal.project or to the key cabal-project-local of the configuration of haskell-gha, and remove the file from the repository.'+          exit 1+        fi+        cat >> cabal.project.local <<'EOF'+        jobs: 4+        tests: True+        benchmarks: True++        program-options+          ghc-options: -Werror+        EOF++    - name: Prefer the oldest dependencies+      working-directory: ${{ runner.temp }}/haskell-gha+      run: |+        echo 'prefer-oldest: True' >> cabal.project.local++    - name: Enable parallel module builds for the local packages+      if: contains(fromJSON('["9.6.7"]'), matrix.ghc)+      working-directory: ${{ runner.temp }}/haskell-gha+      run: |+        cat >> cabal.project.local <<'EOF'+        program-options+          ghc-options: -j4+        EOF++    - name: Enable the GHC job semaphore or parallel module builds+      if: contains(fromJSON('["9.10","9.12"]'), matrix.ghc)+      working-directory: ${{ runner.temp }}/haskell-gha+      run: |+        if ghc --info | grep -F '("Semaphore version","2")' > /dev/null; then+        echo 'GHC uses version 2 of the semaphore protocol and cabal version 1, so GHC uses -j4.'+        cat >> cabal.project.local <<'EOF'+        program-options+          ghc-options: -j4+        EOF+        else+        echo 'GHC and cabal use version 1 of the semaphore protocol, so GHC uses the semaphore.'+        cat >> cabal.project.local <<'EOF'+        semaphore: True+        EOF+        fi++    - name: Make the build plan+      id: plan+      working-directory: ${{ runner.temp }}/haskell-gha+      run: |+        cabal build all --dry-run+        echo "hash=$(sha256sum dist-newstyle/cache/plan.json | cut -d ' ' -f 1)" >> "$GITHUB_OUTPUT"++    - uses: actions/cache/restore@v6+      id: cache+      with:+        path: ${{ steps.setup.outputs.cabal-store }}+        key: haskell-gha.yaml-v1-${{ runner.os }}-${{ runner.arch }}-${{ steps.versions.outputs.image }}-ghc-${{ steps.setup.outputs.ghc-version }}-oldest-${{ steps.plan.outputs.hash }}+        restore-keys: haskell-gha.yaml-v1-${{ runner.os }}-${{ runner.arch }}-${{ steps.versions.outputs.image }}-ghc-${{ steps.setup.outputs.ghc-version }}-oldest-++    - name: Build the dependencies+      working-directory: ${{ runner.temp }}/haskell-gha+      run: |+        cabal build all --only-dependencies++    - uses: actions/cache/save@v6+      if: steps.cache.outputs.cache-hit != 'true'+      with:+        path: ${{ steps.setup.outputs.cabal-store }}+        key: ${{ steps.cache.outputs.cache-primary-key }}++    - name: Build+      working-directory: ${{ runner.temp }}/haskell-gha+      run: |+        cabal build all++    - name: Run the tests+      working-directory: ${{ runner.temp }}/haskell-gha+      run: |+        cabal test all --test-show-details=direct++    - name: Check the packages+      working-directory: ${{ runner.temp }}/haskell-gha+      run: |+        failed=0+        check() {+          echo "Checking the package $1"+          (cd "$2" && cabal check) || { echo "::error::cabal check failed for the package $1"; failed=1; }+        }+        check oldest .+        exit "$failed"++    - name: Build the documentation+      working-directory: ${{ runner.temp }}/haskell-gha+      run: |+        cabal haddock all --disable-documentation --haddock-for-hackage
+ tests/golden/oldest/haskell-gha.conf.yaml view
@@ -0,0 +1,1 @@+dependencies: oldest
+ tests/golden/oldest/oldest.cabal view
@@ -0,0 +1,9 @@+cabal-version: 3.0+name:               oldest+version: 0+tested-with: GHC == 9.6.7 || ^>= { 9.10, 9.12 }+library+  exposed-modules: M+test-suite test+  type: exitcode-stdio-1.0+  main-is: Main.hs
+ tests/golden/project-dir/args view
@@ -0,0 +1,1 @@+--project-dir sub
+ tests/golden/project-dir/expected.yaml view
@@ -0,0 +1,198 @@+# Do not edit this file, it was generated by the following command:+#   haskell-gha --generate --project-dir sub --config haskell-gha.conf.yaml+#+# To regenerate it, run from the root of the repository:+#   haskell-gha+#+# For more information, see https://github.com/arybczak/haskell-gha++name: CI++on:+  push:+    branches:+    - master+    - main+  pull_request:+  merge_group:+  workflow_dispatch:++permissions:+  contents: read++concurrency:+  group: ${{ github.workflow_ref }}+  cancel-in-progress: true++defaults:+  run:+    shell: bash+    working-directory: sub++jobs:+  fourmolu:+    name: Fourmolu+    runs-on: ubuntu-26.04+    timeout-minutes: 60+    steps:+    - uses: actions/checkout@v7+      with:+        persist-credentials: false++    - uses: haskell-actions/run-fourmolu@v13+      with:+        version: '0.21.0.0'+        working-directory: sub++  hlint:+    name: HLint+    runs-on: ubuntu-26.04+    timeout-minutes: 60+    steps:+    - uses: actions/checkout@v7+      with:+        persist-credentials: false++    - uses: haskell-actions/hlint-setup@c04631035af0a6787c85e33b3ea0128b8568b590+      with:+        version: '3.10'++    - uses: haskell-actions/hlint-run@d009541bdae0b8492992416e665bb6df8a3b5cde+      with:+        path: 'sub'+        fail-on: suggestion++  build:+    name: GHC ${{ matrix.ghc }}+    runs-on: ubuntu-26.04+    timeout-minutes: 60+    strategy:+      fail-fast: false+      matrix:+        ghc:+        - '9.12'+    steps:+    - uses: actions/checkout@v7+      with:+        persist-credentials: false+        submodules: true++    - name: Install GHC and cabal+      id: setup+      run: |+        mkdir -p "$RUNNER_TEMP"/.ghcup/bin+        curl -fsSL -o "$RUNNER_TEMP"/.ghcup/bin/ghcup "https://downloads.haskell.org/ghcup/$(uname -m)-linux-ghcup"+        chmod +x "$RUNNER_TEMP"/.ghcup/bin/ghcup+        export GHCUP_INSTALL_BASE_PREFIX="$RUNNER_TEMP" PATH="$RUNNER_TEMP/.ghcup/bin:$PATH"+        echo "GHCUP_INSTALL_BASE_PREFIX=$RUNNER_TEMP" >> "$GITHUB_ENV"+        echo "$RUNNER_TEMP/.ghcup/bin" >> "$GITHUB_PATH"+        versions=$(ghcup -s vanilla list -t ghc -r)+        if grep -qF -e 'ghc ${{ matrix.ghc }} ' -e 'ghc ${{ matrix.ghc }}.' <<< "$versions"; then+          channel=vanilla+        else+          echo 'The vanilla channel of GHCup has no GHC ${{ matrix.ghc }}, so the step uses the prerelease channel.'+          channel=prereleases+        fi+        ghcup -s "$channel" install ghc '${{ matrix.ghc }}' --set+        ghcup -s vanilla install cabal 3.16.1.0 --set+        cabal update+        echo "ghc-version=$(ghc --numeric-version)" >> "$GITHUB_OUTPUT"+        echo "cabal-version=$(cabal --numeric-version)" >> "$GITHUB_OUTPUT"+        echo "cabal-store=$(cabal path -z --store-dir)" >> "$GITHUB_OUTPUT"++    - name: Show the versions+      id: versions+      run: |+        ghc --version+        cabal --version+        echo "GHC ${{ steps.setup.outputs.ghc-version }}, cabal ${{ steps.setup.outputs.cabal-version }}, image $ImageOS $ImageVersion" >> "$GITHUB_STEP_SUMMARY"+        echo "image=$ImageOS" >> "$GITHUB_OUTPUT"++    - name: Unpack the source tarballs+      run: |+        shopt -s extglob+        cabal sdist all --output-directory="$RUNNER_TEMP"/haskell-gha-sdist+        mkdir "$RUNNER_TEMP"/haskell-gha+        for f in cabal.project cabal.project.freeze cabal.project.local; do+          if [ -f "$f" ]; then cp "$f" "$RUNNER_TEMP"/haskell-gha; fi+        done+        mkdir -p "$RUNNER_TEMP"/haskell-gha/app+        tar -xzf "$RUNNER_TEMP"/haskell-gha-sdist/app-+([0-9.]).tar.gz --strip-components=1 -C "$RUNNER_TEMP"/haskell-gha/app++    - name: Configure the project+      working-directory: ${{ runner.temp }}/haskell-gha+      run: |+        if [ -f cabal.project.local ]; then+          echo '::error::The repository contains cabal.project.local, which holds the settings of one developer. Move the settings to cabal.project or to the key cabal-project-local of the configuration of haskell-gha, and remove the file from the repository.'+          exit 1+        fi+        cat >> cabal.project.local <<'EOF'+        jobs: 4+        tests: True+        benchmarks: True++        program-options+          ghc-options: -Werror+        EOF++    - name: Enable the GHC job semaphore or parallel module builds+      working-directory: ${{ runner.temp }}/haskell-gha+      run: |+        if ghc --info | grep -F '("Semaphore version","2")' > /dev/null; then+        echo 'GHC uses version 2 of the semaphore protocol and cabal version 1, so GHC uses -j4.'+        cat >> cabal.project.local <<'EOF'+        program-options+          ghc-options: -j4+        EOF+        else+        echo 'GHC and cabal use version 1 of the semaphore protocol, so GHC uses the semaphore.'+        cat >> cabal.project.local <<'EOF'+        semaphore: True+        EOF+        fi++    - name: Make the build plan+      id: plan+      working-directory: ${{ runner.temp }}/haskell-gha+      run: |+        cabal build all --dry-run+        echo "hash=$(sha256sum dist-newstyle/cache/plan.json | cut -d ' ' -f 1)" >> "$GITHUB_OUTPUT"++    - uses: actions/cache/restore@v6+      id: cache+      with:+        path: ${{ steps.setup.outputs.cabal-store }}+        key: haskell-gha.yaml-v1-${{ runner.os }}-${{ runner.arch }}-${{ steps.versions.outputs.image }}-ghc-${{ steps.setup.outputs.ghc-version }}-newest-${{ steps.plan.outputs.hash }}+        restore-keys: haskell-gha.yaml-v1-${{ runner.os }}-${{ runner.arch }}-${{ steps.versions.outputs.image }}-ghc-${{ steps.setup.outputs.ghc-version }}-newest-++    - name: Build the dependencies+      working-directory: ${{ runner.temp }}/haskell-gha+      run: |+        cabal build all --only-dependencies++    - uses: actions/cache/save@v6+      if: steps.cache.outputs.cache-hit != 'true'+      with:+        path: ${{ steps.setup.outputs.cabal-store }}+        key: ${{ steps.cache.outputs.cache-primary-key }}++    - name: Build+      working-directory: ${{ runner.temp }}/haskell-gha+      run: |+        cabal build all++    - name: Check the packages+      working-directory: ${{ runner.temp }}/haskell-gha+      run: |+        failed=0+        check() {+          echo "Checking the package $1"+          (cd "$2" && cabal check) || { echo "::error::cabal check failed for the package $1"; failed=1; }+        }+        check app app+        exit "$failed"++    - name: Build the documentation+      working-directory: ${{ runner.temp }}/haskell-gha+      run: |+        cabal haddock all --disable-documentation --haddock-for-hackage
+ tests/golden/project-dir/haskell-gha.conf.yaml view
@@ -0,0 +1,7 @@+# Fourmolu and HLint with only the required keys.+fourmolu:+  version: 0.21.0.0+hlint:+  version: '3.10'+# Only the build job fetches the submodules.+submodules: true
+ tests/golden/project-dir/sub/app/app.cabal view
@@ -0,0 +1,7 @@+cabal-version: 3.0+name:          app+version:       0+tested-with:   GHC ^>= 9.12++executable app+  main-is: Main.hs
+ tests/golden/project-dir/sub/cabal.project view
@@ -0,0 +1,1 @@+packages: app
+ tests/golden/readme/expected.yaml view
@@ -0,0 +1,255 @@+# Do not edit this file, it was generated by the following command:+#   haskell-gha --generate --config haskell-gha.conf.yaml+#+# To regenerate it, run from the root of the repository:+#   haskell-gha+#+# For more information, see https://github.com/arybczak/haskell-gha++name: CI++on:+  push:+    branches:+    - master+  pull_request:+  merge_group:+  workflow_dispatch:++permissions:+  contents: read++concurrency:+  group: ${{ github.workflow_ref }}+  cancel-in-progress: true++defaults:+  run:+    shell: bash++jobs:+  fourmolu:+    name: Fourmolu+    runs-on: ubuntu-26.04+    timeout-minutes: 60+    steps:+    - uses: actions/checkout@v7+      with:+        persist-credentials: false++    - uses: haskell-actions/run-fourmolu@v13+      with:+        version: '0.21.0.0'++  build:+    name: 'GHC ${{ matrix.ghc }}, ${{ matrix.dependencies }}'+    runs-on: ubuntu-26.04+    timeout-minutes: 60+    services:+      postgres:+        image: postgres:18+        env:+          POSTGRES_PASSWORD: postgres+        ports:+        - '5432:5432'+        options: >-+          --health-cmd pg_isready+          --health-interval 5s+          --health-retries 10+    strategy:+      fail-fast: false+      matrix:+        ghc:+        - '9.6.7'+        - '9.10'+        - '9.12'+        dependencies:+        - newest+        - oldest+    steps:+    - uses: actions/checkout@v7+      with:+        persist-credentials: false++    - name: Install the system packages+      run: |+        sudo apt-get update+        sudo DEBIAN_FRONTEND=noninteractive apt-get install -y --no-install-recommends libsodium-dev++    - name: Install GHC and cabal+      id: setup+      run: |+        mkdir -p "$RUNNER_TEMP"/.ghcup/bin+        curl -fsSL -o "$RUNNER_TEMP"/.ghcup/bin/ghcup "https://downloads.haskell.org/ghcup/$(uname -m)-linux-ghcup"+        chmod +x "$RUNNER_TEMP"/.ghcup/bin/ghcup+        export GHCUP_INSTALL_BASE_PREFIX="$RUNNER_TEMP" PATH="$RUNNER_TEMP/.ghcup/bin:$PATH"+        echo "GHCUP_INSTALL_BASE_PREFIX=$RUNNER_TEMP" >> "$GITHUB_ENV"+        echo "$RUNNER_TEMP/.ghcup/bin" >> "$GITHUB_PATH"+        versions=$(ghcup -s vanilla list -t ghc -r)+        if grep -qF -e 'ghc ${{ matrix.ghc }} ' -e 'ghc ${{ matrix.ghc }}.' <<< "$versions"; then+          channel=vanilla+        else+          echo 'The vanilla channel of GHCup has no GHC ${{ matrix.ghc }}, so the step uses the prerelease channel.'+          channel=prereleases+        fi+        ghcup -s "$channel" install ghc '${{ matrix.ghc }}' --set+        ghcup -s vanilla install cabal 3.16.1.0 --set+        cabal update+        echo "ghc-version=$(ghc --numeric-version)" >> "$GITHUB_OUTPUT"+        echo "cabal-version=$(cabal --numeric-version)" >> "$GITHUB_OUTPUT"+        echo "cabal-store=$(cabal path -z --store-dir)" >> "$GITHUB_OUTPUT"++    - name: Show the versions+      id: versions+      run: |+        ghc --version+        cabal --version+        echo "GHC ${{ steps.setup.outputs.ghc-version }}, cabal ${{ steps.setup.outputs.cabal-version }}, image $ImageOS $ImageVersion" >> "$GITHUB_STEP_SUMMARY"+        echo "image=$ImageOS" >> "$GITHUB_OUTPUT"++    - name: Unpack the source tarballs+      run: |+        shopt -s extglob+        cabal sdist all --output-directory="$RUNNER_TEMP"/haskell-gha-sdist+        mkdir "$RUNNER_TEMP"/haskell-gha+        for f in cabal.project cabal.project.freeze cabal.project.local; do+          if [ -f "$f" ]; then cp "$f" "$RUNNER_TEMP"/haskell-gha; fi+        done+        tar -xzf "$RUNNER_TEMP"/haskell-gha-sdist/readme-+([0-9.]).tar.gz --strip-components=1 -C "$RUNNER_TEMP"/haskell-gha++    - name: Configure the project+      working-directory: ${{ runner.temp }}/haskell-gha+      run: |+        if [ -f cabal.project.local ]; then+          echo '::error::The repository contains cabal.project.local, which holds the settings of one developer. Move the settings to cabal.project or to the key cabal-project-local of the configuration of haskell-gha, and remove the file from the repository.'+          exit 1+        fi+        cat >> cabal.project.local <<'EOF'+        jobs: 4+        tests: True+        benchmarks: True+        write-ghc-environment-files: always++        program-options+          ghc-options: -Werror+        EOF++    - name: Prefer the oldest dependencies+      if: matrix.dependencies == 'oldest'+      working-directory: ${{ runner.temp }}/haskell-gha+      run: |+        echo 'prefer-oldest: True' >> cabal.project.local++    - name: Enable parallel module builds for the local packages+      if: contains(fromJSON('["9.6.7"]'), matrix.ghc)+      working-directory: ${{ runner.temp }}/haskell-gha+      run: |+        cat >> cabal.project.local <<'EOF'+        program-options+          ghc-options: -j4+        EOF++    - name: Enable the GHC job semaphore or parallel module builds+      if: contains(fromJSON('["9.10","9.12"]'), matrix.ghc)+      working-directory: ${{ runner.temp }}/haskell-gha+      run: |+        if ghc --info | grep -F '("Semaphore version","2")' > /dev/null; then+        echo 'GHC uses version 2 of the semaphore protocol and cabal version 1, so GHC uses -j4.'+        cat >> cabal.project.local <<'EOF'+        program-options+          ghc-options: -j4+        EOF+        else+        echo 'GHC and cabal use version 1 of the semaphore protocol, so GHC uses the semaphore.'+        cat >> cabal.project.local <<'EOF'+        semaphore: True+        EOF+        fi++    - name: Make the build plan+      id: plan+      working-directory: ${{ runner.temp }}/haskell-gha+      run: |+        cabal build all --dry-run+        echo "hash=$(sha256sum dist-newstyle/cache/plan.json | cut -d ' ' -f 1)" >> "$GITHUB_OUTPUT"++    - uses: actions/cache/restore@v6+      id: cache+      with:+        path: ${{ steps.setup.outputs.cabal-store }}+        key: haskell-gha.yaml-v1-${{ runner.os }}-${{ runner.arch }}-${{ steps.versions.outputs.image }}-ghc-${{ steps.setup.outputs.ghc-version }}-${{ matrix.dependencies }}-${{ steps.plan.outputs.hash }}+        restore-keys: haskell-gha.yaml-v1-${{ runner.os }}-${{ runner.arch }}-${{ steps.versions.outputs.image }}-ghc-${{ steps.setup.outputs.ghc-version }}-${{ matrix.dependencies }}-++    - name: Build the dependencies+      working-directory: ${{ runner.temp }}/haskell-gha+      run: |+        cabal build all --only-dependencies++    - uses: actions/cache/save@v6+      if: steps.cache.outputs.cache-hit != 'true'+      with:+        path: ${{ steps.setup.outputs.cabal-store }}+        key: ${{ steps.cache.outputs.cache-primary-key }}++    - name: Find the doctest version+      id: doctest+      run: |+        version=$(cabal --store-dir="$RUNNER_TEMP"/doctest-store install doctest --ignore-project --dry-run | sed -n 's/^ - doctest-\([0-9.]*\) (exe:doctest).*/\1/p')+        if [ -z "$version" ]; then+          echo 'The dry run of cabal install shows no doctest version.' >&2+          exit 1+        fi+        echo "version=$version" >> "$GITHUB_OUTPUT"++    - uses: actions/cache/restore@v6+      id: doctest-cache+      with:+        path: ~/.local/bin/doctest+        key: haskell-gha-v1-${{ runner.os }}-${{ runner.arch }}-${{ steps.versions.outputs.image }}-doctest-${{ steps.doctest.outputs.version }}-ghc-${{ steps.setup.outputs.ghc-version }}++    - name: Install doctest+      if: steps.doctest-cache.outputs.cache-hit != 'true'+      run: |+        cabal install doctest --ignore-project --install-method=copy --installdir="$HOME/.local/bin" --overwrite-policy=always --constraint='doctest ==${{ steps.doctest.outputs.version }}'++    - uses: actions/cache/save@v6+      if: steps.doctest-cache.outputs.cache-hit != 'true'+      with:+        path: ~/.local/bin/doctest+        key: ${{ steps.doctest-cache.outputs.cache-primary-key }}++    - name: Build+      working-directory: ${{ runner.temp }}/haskell-gha+      run: |+        cabal build all++    - name: Create the test database+      run: psql -h localhost -U postgres -c 'CREATE DATABASE test'+      env:+        PGPASSWORD: postgres++    - name: Run the tests+      working-directory: ${{ runner.temp }}/haskell-gha+      run: |+        cabal test all --test-show-details=direct++    - name: Run doctest for readme+      working-directory: ${{ runner.temp }}/haskell-gha+      run: |+        "$HOME"/.local/bin/doctest -XGHC2021 src++    - name: Check the packages+      working-directory: ${{ runner.temp }}/haskell-gha+      run: |+        failed=0+        check() {+          echo "Checking the package $1"+          (cd "$2" && cabal check) || { echo "::error::cabal check failed for the package $1"; failed=1; }+        }+        check readme .+        exit "$failed"++    - name: Build the documentation+      working-directory: ${{ runner.temp }}/haskell-gha+      run: |+        cabal haddock all --disable-documentation --haddock-for-hackage
+ tests/golden/readme/haskell-gha.conf.yaml view
@@ -0,0 +1,22 @@+branches: [master]+apt: [libsodium-dev]+dependencies: both+services:+  postgres:+    image: postgres:18+    env:+      POSTGRES_PASSWORD: postgres+    ports: ['5432:5432']+    options: >-+      --health-cmd pg_isready+      --health-interval 5s+      --health-retries 10+hooks:+  after-build:+  - name: Create the test database+    run: psql -h localhost -U postgres -c 'CREATE DATABASE test'+    env:+      PGPASSWORD: postgres+doctest: {}+fourmolu:+  version: 0.21.0.0
+ tests/golden/readme/readme.cabal view
@@ -0,0 +1,14 @@+cabal-version: 3.0+name:          readme+version:       0+tested-with:   GHC == 9.6.7 || ^>= 9.10 || ^>= 9.12++library+  hs-source-dirs:   src+  exposed-modules:  Readme+  default-language: GHC2021++test-suite test+  type:           exitcode-stdio-1.0+  hs-source-dirs: test+  main-is:        Main.hs
+ tests/golden/single/example.cabal view
@@ -0,0 +1,9 @@+cabal-version: 3.0+name: example+version: 0+tested-with: GHC == 9.6.7 || ^>= { 9.10, 9.12 }+library+  exposed-modules: M+test-suite test+  type: exitcode-stdio-1.0+  main-is: Main.hs
+ tests/golden/single/expected.yaml view
@@ -0,0 +1,180 @@+# Do not edit this file, it was generated by the following command:+#   haskell-gha --generate+#+# To regenerate it, run from the root of the repository:+#   haskell-gha+#+# For more information, see https://github.com/arybczak/haskell-gha++name: CI++on:+  push:+    branches:+    - master+    - main+  pull_request:+  merge_group:+  workflow_dispatch:++permissions:+  contents: read++concurrency:+  group: ${{ github.workflow_ref }}+  cancel-in-progress: true++defaults:+  run:+    shell: bash++jobs:+  build:+    name: GHC ${{ matrix.ghc }}+    runs-on: ubuntu-26.04+    timeout-minutes: 60+    strategy:+      fail-fast: false+      matrix:+        ghc:+        - '9.6.7'+        - '9.10'+        - '9.12'+    steps:+    - uses: actions/checkout@v7+      with:+        persist-credentials: false++    - name: Install GHC and cabal+      id: setup+      run: |+        mkdir -p "$RUNNER_TEMP"/.ghcup/bin+        curl -fsSL -o "$RUNNER_TEMP"/.ghcup/bin/ghcup "https://downloads.haskell.org/ghcup/$(uname -m)-linux-ghcup"+        chmod +x "$RUNNER_TEMP"/.ghcup/bin/ghcup+        export GHCUP_INSTALL_BASE_PREFIX="$RUNNER_TEMP" PATH="$RUNNER_TEMP/.ghcup/bin:$PATH"+        echo "GHCUP_INSTALL_BASE_PREFIX=$RUNNER_TEMP" >> "$GITHUB_ENV"+        echo "$RUNNER_TEMP/.ghcup/bin" >> "$GITHUB_PATH"+        versions=$(ghcup -s vanilla list -t ghc -r)+        if grep -qF -e 'ghc ${{ matrix.ghc }} ' -e 'ghc ${{ matrix.ghc }}.' <<< "$versions"; then+          channel=vanilla+        else+          echo 'The vanilla channel of GHCup has no GHC ${{ matrix.ghc }}, so the step uses the prerelease channel.'+          channel=prereleases+        fi+        ghcup -s "$channel" install ghc '${{ matrix.ghc }}' --set+        ghcup -s vanilla install cabal 3.16.1.0 --set+        cabal update+        echo "ghc-version=$(ghc --numeric-version)" >> "$GITHUB_OUTPUT"+        echo "cabal-version=$(cabal --numeric-version)" >> "$GITHUB_OUTPUT"+        echo "cabal-store=$(cabal path -z --store-dir)" >> "$GITHUB_OUTPUT"++    - name: Show the versions+      id: versions+      run: |+        ghc --version+        cabal --version+        echo "GHC ${{ steps.setup.outputs.ghc-version }}, cabal ${{ steps.setup.outputs.cabal-version }}, image $ImageOS $ImageVersion" >> "$GITHUB_STEP_SUMMARY"+        echo "image=$ImageOS" >> "$GITHUB_OUTPUT"++    - name: Unpack the source tarballs+      run: |+        shopt -s extglob+        cabal sdist all --output-directory="$RUNNER_TEMP"/haskell-gha-sdist+        mkdir "$RUNNER_TEMP"/haskell-gha+        for f in cabal.project cabal.project.freeze cabal.project.local; do+          if [ -f "$f" ]; then cp "$f" "$RUNNER_TEMP"/haskell-gha; fi+        done+        tar -xzf "$RUNNER_TEMP"/haskell-gha-sdist/example-+([0-9.]).tar.gz --strip-components=1 -C "$RUNNER_TEMP"/haskell-gha++    - name: Configure the project+      working-directory: ${{ runner.temp }}/haskell-gha+      run: |+        if [ -f cabal.project.local ]; then+          echo '::error::The repository contains cabal.project.local, which holds the settings of one developer. Move the settings to cabal.project or to the key cabal-project-local of the configuration of haskell-gha, and remove the file from the repository.'+          exit 1+        fi+        cat >> cabal.project.local <<'EOF'+        jobs: 4+        tests: True+        benchmarks: True++        program-options+          ghc-options: -Werror+        EOF++    - name: Enable parallel module builds for the local packages+      if: contains(fromJSON('["9.6.7"]'), matrix.ghc)+      working-directory: ${{ runner.temp }}/haskell-gha+      run: |+        cat >> cabal.project.local <<'EOF'+        program-options+          ghc-options: -j4+        EOF++    - name: Enable the GHC job semaphore or parallel module builds+      if: contains(fromJSON('["9.10","9.12"]'), matrix.ghc)+      working-directory: ${{ runner.temp }}/haskell-gha+      run: |+        if ghc --info | grep -F '("Semaphore version","2")' > /dev/null; then+        echo 'GHC uses version 2 of the semaphore protocol and cabal version 1, so GHC uses -j4.'+        cat >> cabal.project.local <<'EOF'+        program-options+          ghc-options: -j4+        EOF+        else+        echo 'GHC and cabal use version 1 of the semaphore protocol, so GHC uses the semaphore.'+        cat >> cabal.project.local <<'EOF'+        semaphore: True+        EOF+        fi++    - name: Make the build plan+      id: plan+      working-directory: ${{ runner.temp }}/haskell-gha+      run: |+        cabal build all --dry-run+        echo "hash=$(sha256sum dist-newstyle/cache/plan.json | cut -d ' ' -f 1)" >> "$GITHUB_OUTPUT"++    - uses: actions/cache/restore@v6+      id: cache+      with:+        path: ${{ steps.setup.outputs.cabal-store }}+        key: haskell-gha.yaml-v1-${{ runner.os }}-${{ runner.arch }}-${{ steps.versions.outputs.image }}-ghc-${{ steps.setup.outputs.ghc-version }}-newest-${{ steps.plan.outputs.hash }}+        restore-keys: haskell-gha.yaml-v1-${{ runner.os }}-${{ runner.arch }}-${{ steps.versions.outputs.image }}-ghc-${{ steps.setup.outputs.ghc-version }}-newest-++    - name: Build the dependencies+      working-directory: ${{ runner.temp }}/haskell-gha+      run: |+        cabal build all --only-dependencies++    - uses: actions/cache/save@v6+      if: steps.cache.outputs.cache-hit != 'true'+      with:+        path: ${{ steps.setup.outputs.cabal-store }}+        key: ${{ steps.cache.outputs.cache-primary-key }}++    - name: Build+      working-directory: ${{ runner.temp }}/haskell-gha+      run: |+        cabal build all++    - name: Run the tests+      working-directory: ${{ runner.temp }}/haskell-gha+      run: |+        cabal test all --test-show-details=direct++    - name: Check the packages+      working-directory: ${{ runner.temp }}/haskell-gha+      run: |+        failed=0+        check() {+          echo "Checking the package $1"+          (cd "$2" && cabal check) || { echo "::error::cabal check failed for the package $1"; failed=1; }+        }+        check example .+        exit "$failed"++    - name: Build the documentation+      working-directory: ${{ runner.temp }}/haskell-gha+      run: |+        cabal haddock all --disable-documentation --haddock-for-hackage