packages feed

cabal-flatpak-1.0.0: src/domain/Distribution/Flatpak/App.hs

module Distribution.Flatpak.App
  ( App (..)
  , Repository (..)
  , fromGeneric
  , parseApp
  , command
  ) where

import Data.ByteString (ByteString)
import Data.Foldable (toList)
import Data.Maybe
import Data.Text (Text)
import Data.Text qualified as T
import Distribution.PackageDescription
import Distribution.PackageDescription.Parsec
import Distribution.Parsec.Error
import Distribution.Pretty
import Distribution.Utils.ShortText

data App = App
  { name :: Text
  , version :: Text
  , synopsis :: Text
  , description :: Text
  , license :: Text
  , maintainer :: Text
  , author :: Text
  , homepage :: Maybe Text
  , sourceRepo :: Maybe Repository
  , executables :: [Text]
  }
  deriving stock (Show, Eq)

data Repository = Repository
  { location :: Text
  , git :: Bool
  }
  deriving stock (Show, Eq)

fromGeneric :: GenericPackageDescription -> App
fromGeneric gpd =
  App
    { name = T.pack (unPackageName pkg.pkgName)
    , version = T.pack (prettyShow pkg.pkgVersion)
    , synopsis = shortText pd.synopsis
    , description = shortText pd.description
    , license = T.pack (prettyShow (license pd))
    , maintainer = shortText pd.maintainer
    , author = shortText pd.author
    , homepage = nonEmpty (shortText pd.homepage)
    , sourceRepo = listToMaybe (mapMaybe headLocation pd.sourceRepos)
    , executables = map (T.pack . unUnqualComponentName . fst) gpd.condExecutables
    }
  where
    pd = gpd.packageDescription
    pkg = pd.package
    shortText = T.pack . fromShortText
    nonEmpty s = if T.null s then Nothing else Just s
    headLocation = \case
      SourceRepo {repoKind = RepoHead, repoLocation = Just loc, repoType} ->
        Just Repository {location = T.pack loc, git = repoType == Just (KnownRepoType Git)}
      _ -> Nothing

parseApp :: FilePath -> ByteString -> Either Text App
parseApp path bytes =
  case runParseResult (parseGenericPackageDescription bytes) of
    (_, Right gpd) -> Right (fromGeneric gpd)
    (_, Left (_, errors)) -> Left (T.intercalate "\n" (map (\e -> T.pack (showPError path e.perror)) (toList errors)))

command :: App -> Maybe Text
command app
  | app.name `elem` app.executables = Just app.name
  | [only] <- app.executables = Just only
  | otherwise = Nothing