packages feed

haskell-gha-1.0: tests/HaskellGha/Test/Config.hs

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