packages feed

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

module Application.Retrieve
  ( ghcHashes
  , ghcHash
  ) where

import Control.Exception
import Control.Monad
import Data.ByteString.Char8 qualified as B
import Data.ByteString.Lazy.Char8 qualified as BL
import Data.List.HT qualified as ListHT
import Data.Map (Map)
import Data.Map qualified as Map
import Data.Text.Encoding qualified as TextEnc
import Data.Tuple.HT
import Network.HTTP.Client qualified as Http
import Network.HTTP.Client.TLS
import Network.HTTP.Types.Status
import Text.Printf

import Cabal.Plan qualified as Plan
import Distribution.Flatpak qualified as Flatpak
import Distribution.Flatpak.GHC

httpsGet :: String -> IO BL.ByteString
httpsGet url =
  get `catch` (fail . httpError)
  where
    get = do
      request <- Http.parseUrlThrow url
      manager <- getGlobalManager
      Http.responseBody <$> Http.httpLbs request manager
    httpError = \case
      Http.HttpExceptionRequest _ (Http.StatusCodeException response _) ->
        url <> ": HTTP " <> show (statusCode (Http.responseStatus response))
      Http.HttpExceptionRequest _ content -> url <> ": " <> show content
      Http.InvalidUrlException _ reason -> url <> ": invalid URL: " <> reason

ghcHashes :: Plan.PkgId -> IO (String, Map BL.ByteString BL.ByteString)
ghcHashes compiler = do
  let sha256Url = ghcDirUrl compiler ++ "SHA256SUMS"
  ghcSha256s <- httpsGet sha256Url
  let (ghcSha256Map, ghcSha256Corrupts) =
        mapFst Map.fromList $
          ListHT.partitionMaybe
            ( \line ->
                case BL.words line of
                  [hash, archive] -> Just (archive, hash)
                  _ -> Nothing
            )
            (BL.lines ghcSha256s)
  when (not $ null ghcSha256Corrupts)
    $ fail
    $ unlines
    $ (printf "corrupt lines in %s:" sha256Url)
      : map BL.unpack ghcSha256Corrupts
  return (sha256Url, ghcSha256Map)

ghcHash
  :: (String, Map BL.ByteString BL.ByteString)
  -> Plan.PkgId
  -> Flatpak.Arch
  -> Either String Plan.Sha256
ghcHash (sha256Url, ghcSha256Map) compiler arch = do
  let ghcName = ghcArchive compiler arch
  let maybeFail msg = maybe (Left msg) Right
  hashStr <-
    maybeFail
      ( printf
          "could not find SHA256 checksum for %s in %s"
          ghcName
          sha256Url
      )
      $ Map.lookup (BL.pack $ "./" ++ ghcName) ghcSha256Map
  sha256 <-
    maybeFail ("could not parse SHA256 checksum " ++ BL.unpack hashStr)
      $ Plan.parseSha256
      $ TextEnc.decodeLatin1
      $ B.concat
      $ BL.toChunks hashStr
  return sha256