packages feed

haskell-gha-1.0: src/HaskellGha/Command.hs

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