packages feed

haskell-gha-1.0: src/HaskellGha/Workflow/Script.hs

-- | 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