packages feed

cabal-flatpak-1.0.0: src/application/Application.hs

module Application (run) where

import Algebra.Graph.AdjacencyMap qualified as Graph
import Algebra.Graph.AdjacencyMap.Algorithm qualified as Graph
import Codec.Picture (decodePng, dynamicMap, imageHeight, imageWidth)
import Control.Arrow ((&&&))
import Control.Exception
import Control.Monad
import Data.Aeson qualified as Json
import Data.ByteString (ByteString)
import Data.ByteString qualified as BS
import Data.Char (toLower)
import Data.Foldable (for_, toList)
import Data.List.HT qualified as ListHT
import Data.Map qualified as Map
import Data.Maybe (mapMaybe)
import Data.Set qualified as Set
import Data.Text (Text)
import Data.Text qualified as Text
import Data.Text.Encoding qualified as TextEnc
import Data.Traversable qualified as Trav
import Graphics.NanoSvg (parseSvg)
import Options.Applicative qualified as OP
import Shell.Utility.ParseArgument qualified as ParseArg
import System.Directory qualified as Dir
import System.Exit
import System.FilePath
import System.FilePath qualified as FP
import System.IO
import System.IO.Error
import Text.Printf

import Application.CLI.Option qualified as Option
import Application.LocalPackages
import Application.Retrieve qualified as Retrieve
import Application.Write
import Cabal.Plan qualified as Plan
import Distribution.Flatpak qualified as Flatpak
import Distribution.Flatpak.App
import Distribution.Flatpak.AppId
import Distribution.Flatpak.CabalInstall
import Distribution.Flatpak.Generate qualified as Generate
import Distribution.Flatpak.Stub
import Distribution.Flatpak.UnitKind

-- |
-- Cabal operates on units.
-- A package can have multiple units,
-- for example a library unit and multiple executable units.
-- Each of those units can have its own set of library and executable dependencies.
--
-- However, when downloading packages in Flatpak
-- we don't differentiate between the units
-- and treat all units belonging to the same package as one.
--
-- The below heuristic
-- merges all units belonging to the same package into one package
-- and topologically sorts the packages.
--
-- The heuristic goes as follows:
--
-- 1. Build a map between the unit IDs and the package ID that contains it
-- 2. Get the dependency graph using the cabal-plan API
-- 3. Group all units belonging to the same package
--    and merge their dependencies to obtain package dependencies
-- 4. Topologically sort the packages,
--    or order them by package ID with --cabal-install
-- 5. Take one representative unit for each package
--    and use them to generate haskell-sources.yaml.
--    This is safe to do as long as the rest of the generator
--    uses information that is common to all units in the same package.
--    Those are: uPId, uSha256, uCabalSha256, uType and pkg-revision.
--
-- In certain situations
-- this heuristic can still fail to produce a buildable sequence.
-- For example, we can have two packages as such:
-- Pkg1@(lib1, exe1) and Pkg2@(lib2)
-- where the unit lib2 depends on lib1 and exe1 depends on lib2.
-- Unit-wise, it is possible to sequence the builds of the units
-- that avoids cyclical dependencies.
-- But package-wise, it is not possible.
--
-- It is also not possible to use the qualified name of the component
-- for the 'configure' stage
-- and build a package in multiple parts in multiple Flatpak modules.
-- This is because the Plan.uComps is not precise enough,
-- as the documentation states that in certain situations
-- that field may contain more than one value.
-- In that case it is impossible to determine the precise component name.
dependencyUnits :: Plan.PlanJson -> [Plan.PkgId] -> [Plan.Unit]
dependencyUnits plan pkgs =
  let pkgIdToUnit = Map.fromList $ map (Plan.uPId &&& id) $ Map.elems (Plan.pjUnits plan)
  in filter (isDependency . unitKind) $ map (pkgIdToUnit Map.!) pkgs

packageGraph :: Plan.PlanJson -> Either Text (Graph.AdjacencyMap Plan.PkgId)
packageGraph plan = do
  edges <- traverse packageEdges (Map.toList (Plan.planJsonIdGraph plan))
  pure (Graph.fromAdjacencySets edges)
  where
    packageEdges (unitId, deps) = do
      pkg <- unitIdToPkgId unitId
      depPkgs <- traverse unitIdToPkgId (Set.toList deps)
      pure (pkg, Set.delete pkg (Set.fromList depPkgs))
    unitIdToPkgId unitId@(Plan.UnitId name) =
      maybe
        (Left ("plan.json: unit " <> name <> " is a dependency, but it is not in install-plan"))
        (Right . Plan.uPId)
        (Map.lookup unitId (Plan.pjUnits plan))

buildOrder :: Graph.AdjacencyMap Plan.PkgId -> Either Text [Plan.PkgId]
buildOrder graph =
  case Graph.topSort (Graph.transpose graph) of
    Right pkgs -> Right pkgs
    Left pkgs ->
      Left $
        "packages that depend on each other: "
          <> Text.intercalate ", " (map Plan.dispPkgId (toList pkgs))
          <> "; one Flatpak module per package cannot build them, use --cabal-install"

run :: IO ()
run = reportErrors $ do
  Option.Generate opts <- OP.execParser Option.info
  start <- maybe Dir.getCurrentDirectory pure opts.projectDir
  root <-
    Plan.findProjectRoot start
      >>= maybe (fail ("no cabal project found from " <> start)) pure
  plan <- readPlan root
  let Option.Selection {wantDependencies, wantManifest} = Option.selection opts
  when wantDependencies $ generateDependencies opts root plan
  when wantManifest $ generateStubs opts root plan

minimumCabalVersion :: Plan.Ver
minimumCabalVersion = Plan.Ver [3, 18, 1, 0]

planHint :: Text
planHint = "Create it with: cabal build --dry-run --disable-tests --disable-benchmarks"

readPlan :: FilePath -> IO Plan.PlanJson
readPlan root = do
  let notFound (err :: IOException) =
        fail $ "plan.json not found or unreadable: " <> errorMessage err <> ". " <> Text.unpack planHint
  path <- Plan.findPlanJson (Plan.ProjectRelativeToDir root) `catch` notFound
  bytes <- BS.readFile path `catch` notFound
  plan <- either (fail . ((path <> ": ") <>)) pure (Json.eitherDecodeStrict' bytes)
  let version = Plan.dispVer (Plan.pjCabalVersion plan)
      required = Plan.dispVer minimumCabalVersion
  when (Plan.pjCabalVersion plan < minimumCabalVersion) $
    failLines
      [ "plan.json comes from cabal-install "
          <> version
          <> ", but cabal-flatpak needs "
          <> required
          <> " or later. "
          <> planHint
          <> " with cabal-install "
          <> required
          <> " or later."
      ]
  pure plan

failLines :: [Text] -> IO ()
failLines messages = unless (null messages) $ fail $ Text.unpack $ Text.intercalate "\n" messages

reportErrors :: IO () -> IO ()
reportErrors action =
  action `catch` \(err :: IOException) -> do
    hPutStrLn stderr ("cabal-flatpak: " <> errorMessage err)
    exitFailure

errorMessage :: IOException -> String
errorMessage err
  | isUserError err = ioeGetErrorString err
  | otherwise = show err

readRelaxations :: FilePath -> IO [Text]
readRelaxations root =
  concat <$> traverse (readFileRelaxations . (root </>)) ["cabal.project", "cabal.project.local"]

readFileRelaxations :: FilePath -> IO [Text]
readFileRelaxations path = do
  bytes <-
    BS.readFile path
      `catch` \(err :: IOException) ->
        if isDoesNotExistError err then pure BS.empty else ioError err
  relaxations <- orFail $ projectRelaxations path bytes
  unless (null relaxations.unfollowed)
    $ hPutStrLn stderr
    $ Text.unpack
    $ Text.intercalate "\n"
    $ ( "cabal-flatpak: warning: "
          <> Text.pack path
          <> ": allow-newer and allow-older inside these parts are not copied to the freeze file; add them by hand:"
      )
      : map ("  " <>) relaxations.unfollowed
  pure relaxations.fields

orFail :: Either Text a -> IO a
orFail = either (fail . Text.unpack) return

origin :: Option.GenerateOptions -> Origin
origin opts
  | opts.local = LocalDir
  | otherwise = Forge

generateStubs :: Option.GenerateOptions -> FilePath -> Plan.PlanJson -> IO ()
generateStubs opts root plan = do
  local <- localPackage plan root
  icon <- traverse (mkIconDir root) opts.icon
  let app = local.app
      appId = inferAppId app.name app.homepage
      packageDir = case FP.takeDirectory local.cabalFile of
        "." -> Nothing
        subdir -> Just subdir
      mode
        | opts.cabalInstall = CabalMode
        | otherwise = SetupMode
  for_ (stubFiles (StubContext appId app packageDir mode (origin opts) icon)) $ \(file, content) ->
    writeOrSkip opts.force (root </> file) (TextEnc.encodeUtf8 content)

mkIconDir :: FilePath -> Text -> IO IconInfo
mkIconDir root icon = do
  let iconPath = root </> Text.unpack icon
      ext = toLower <$> takeExtension iconPath
  contents <-
    BS.readFile iconPath `catch` \(err :: IOException) ->
      fail $ "Error reading file " <> iconPath <> ": " <> errorMessage err
  size <- case ext of
    ".svg" -> case parseSvg contents of
      Left err -> fail $ "Error reading SVG image " <> iconPath <> ": " <> err
      _ -> pure "scalable"
    ".png" -> case decodePng contents of
      Left err -> fail $ "Error reading PNG image " <> iconPath <> ": " <> err
      Right image -> do
        let (w, h) = dynamicMap ((,) <$> imageWidth <*> imageHeight) image
        unless (((w == 256) && (h == 256)) || ((w == 512 && h == 512))) $ do
          fail $ "PNG icon must be either 256x256 or 512x512: " <> iconPath <> "."
        pure $ show w <> "x" <> show h
    _ -> fail $ "Unknown file extension '" <> ext <> "' for icon: " <> iconPath
  let dir = "/app/share/icons/hicolor/" <> size <> "/apps/"
  pure $ IconInfo icon (Text.pack ext) dir

generateDependencies :: Option.GenerateOptions -> FilePath -> Plan.PlanJson -> IO ()
generateDependencies opts root plan = do
  let target = root </> haskellSourcesFile (origin opts)
  skipped <- skipExisting opts.force target
  unless skipped $ BS.writeFile target =<< sourcesYaml opts root plan

unsupportedUnit :: Plan.Unit -> Maybe Text
unsupportedUnit unit = case unitKind unit of
  Unsupported source ->
    Just ("package " <> Plan.dispPkgId (Plan.uPId unit) <> " comes from " <> source <> ", which cabal-flatpak does not support")
  (Builtin; Local; Hackage) -> Nothing

isDependency :: UnitKind -> Bool
isDependency = \case
  (Builtin; Local) -> False
  (Hackage; Unsupported _) -> True

sourcesYaml :: Option.GenerateOptions -> FilePath -> Plan.PlanJson -> IO ByteString
sourcesYaml opts root plan = do
  graph <- orFail $ packageGraph plan
  failLines (mapMaybe unsupportedUnit (dependencyUnits plan (Graph.vertexList graph)))
  units <-
    dependencyUnits plan
      <$> if opts.cabalInstall
        then pure (Graph.vertexList graph)
        else orFail (buildOrder graph)

  archs <-
    case Set.toList opts.archs of
      [] ->
        let archStr = Text.unpack $ Plan.pjArch plan
        in maybe
             (fail $ printf "unsupported architecture: %s" archStr)
             (return . (: []))
             $ ParseArg.enumMaybe Flatpak.archString archStr
      archs -> return archs

  let revise unit = do
        revision <- Plan.uRev unit
        _ <- Plan.uCabalSha256 unit
        pure (Generate.RevisedUnit unit revision)
      (revisedUnits, unrevisedUnits) = ListHT.partitionMaybe revise units

  unless (null unrevisedUnits) $
    failLines
      ( "units without a pkg-revision or a .cabal SHA256 in plan.json:"
          : map (Plan.dispPkgId . Plan.uPId) unrevisedUnits
      )

  cabalInputs <-
    if opts.cabalInstall
      then do
        local <- localPackage plan root
        relaxations <- readRelaxations root
        freeze <- orFail $ freezeProject plan relaxations
        pure (Just (freeze, LocalCabal local.app.name local.cabalContents))
      else pure Nothing

  archHashes <- do
    let compiler = Plan.pjCompilerId plan
    sha256Map <- Retrieve.ghcHashes compiler
    either fail return $
      Trav.forM archs $ \arch -> do
        sha256 <- Retrieve.ghcHash sha256Map compiler arch
        return (arch, sha256)

  pure $ Flatpak.encodeYaml $ case cabalInputs of
    Just (freeze, local) -> haskellSourcesCabal plan archHashes freeze local revisedUnits
    Nothing -> Generate.haskellSources plan archHashes revisedUnits