packages feed

hackage-api (empty) → 0.1.0

raw patch · 7 files changed

+298/−0 lines, 7 filesdep +Cabaldep +aesondep +base

Dependencies added: Cabal, aeson, base, bytestring, hackage-api, http-client, http-client-tls, http-media, servant, servant-client, servant-client-core, text, time

Files

+ CHANGELOG.md view
@@ -0,0 +1,5 @@+# hackage-api++## 0.1.0++Initial release
+ LICENSE view
@@ -0,0 +1,11 @@+Copyright (c) 2021 Poscat++Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:++   1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.++   2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.++   3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.++THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ README.md view
@@ -0,0 +1,1 @@+# hackage-api
+ hackage-api.cabal view
@@ -0,0 +1,85 @@+cabal-version:   3.0+name:            hackage-api+version:         0.1.0+synopsis:        An API binding to Hackage API+description:     An (partial) API binding to Hackage API+category:        Distribution+license:         BSD-3-Clause+license-file:    LICENSE+author:          Poscat+maintainer:      Poscat <poscat@mail.poscat.moe>+copyright:       Copyright (c) Poscat 2021+stability:       alpha+homepage:        https://github.com/poscat0x04/hackage-api+bug-reports:     https://github.com/poscat0x04/hackage-api/issues+extra-doc-files:+  CHANGELOG.md+  README.md++common common-attrs+  build-depends:+    , base             >=4.10 && <5+    , http-client-tls+    , servant-client++  default-language:   Haskell2010+  default-extensions:+    NoStarIsType+    BangPatterns+    ConstraintKinds+    DataKinds+    DeriveFoldable+    DeriveFunctor+    DeriveGeneric+    DeriveTraversable+    DuplicateRecordFields+    EmptyCase+    FlexibleContexts+    FlexibleInstances+    FunctionalDependencies+    InstanceSigs+    KindSignatures+    LambdaCase+    MultiWayIf+    OverloadedStrings+    PartialTypeSignatures+    PatternSynonyms+    RecordWildCards+    ScopedTypeVariables+    TupleSections+    TypeApplications+    TypeFamilies+    TypeOperators+    UnicodeSyntax+    ViewPatterns++library+  import:          common-attrs+  build-depends:+    , aeson+    , bytestring+    , Cabal+    , http-client+    , http-media+    , servant+    , servant-client-core+    , text+    , time++  exposed-modules:+    Distribution.Hackage.API+    Distribution.Hackage.Types++  other-modules:+  hs-source-dirs:  src++test-suite hackage-api-test+  import:         common-attrs+  type:           exitcode-stdio-1.0+  build-depends:  hackage-api+  hs-source-dirs: test+  main-is:        Spec.hs++source-repository head+  type:     git+  location: https://github.com/poscat0x04/hackage-api
+ src/Distribution/Hackage/API.hs view
@@ -0,0 +1,25 @@+module Distribution.Hackage.API where++import Data.Proxy+import Distribution.Hackage.Types+import Distribution.PackageDescription+import Network.HTTP.Client (Manager)+import Network.HTTP.Client.TLS+import Servant.API+import Servant.Client++getPackages :: ClientM [Package]+getVersions :: Package -> ClientM Versions+getRevisions :: Package -> ClientM [Revision]+getCabalFile :: Package -> ClientM GenericPackageDescription+getCabalFile' :: Package -> Int -> ClientM GenericPackageDescription+getPackages :<|> getVersions :<|> getRevisions :<|> getCabalFile :<|> getCabalFile' = client (Proxy @HackageAPI)++runClient :: Manager -> ClientM a -> IO (Either ClientError a)+runClient manager m = do+  url <- parseBaseUrl "https://hackage.haskell.org/"+  let env = mkClientEnv manager url+  runClientM m env++runClient' :: ClientM a -> IO (Either ClientError a)+runClient' m = newTlsManager >>= flip runClient m
+ src/Distribution/Hackage/Types.hs view
@@ -0,0 +1,141 @@+{-# LANGUAGE DeriveAnyClass #-}+{-# LANGUAGE DerivingStrategies #-}+{-# LANGUAGE GeneralizedNewtypeDeriving #-}+{-# LANGUAGE StrictData #-}++module Distribution.Hackage.Types where++import Data.Aeson+import Data.ByteString.Lazy (toStrict)+import Data.Function+import Data.List.NonEmpty (toList)+import Data.Maybe+import Data.Proxy+import Data.Text (Text, unpack)+import Data.Time+import Distribution.PackageDescription+import Distribution.PackageDescription.Parsec+import Distribution.Parsec+import GHC.Generics (Generic)+import Network.HTTP.Media ((//), (/:))+import Servant.API+import Servant.API.ContentTypes+import Servant.Client+import Servant.Client.Core++data JSON0++instance Accept JSON0 where+  contentType _ = "application/json"++instance FromJSON a => MimeUnrender JSON0 a where+  mimeUnrender _ = eitherDecodeLenient++-----------------------------------------------------------++newtype Time = Time UTCTime+  deriving newtype (Show, Eq)++instance FromJSON Time where+  parseJSON = withText "time" $ \t ->+    case parseTimeM False defaultTimeLocale (iso8601DateFormat (Just "%T%Z")) (unpack t) of+      Just time -> pure $ Time time+      Nothing -> fail "failed to parse time"++data Version+  = Default+  | Version Text+  deriving (Show, Eq, Generic)++instance FromJSON Version where+  parseJSON = withText "version" $ pure . Version++data Package = Package+  { packageName :: Text,+    version :: Version+  }+  deriving (Show, Eq, Generic)++instance FromJSON Package where+  parseJSON = withObject "package" $ \o -> do+    packageName <- o .: "packageName"+    let version = Default+    pure $ Package {..}++instance ToHttpApiData Package where+  toUrlPiece Package {..}+    | Default <- version = packageName+    | Version ver <- version = packageName <> "-" <> ver++data Revision = Revision+  { time :: Time,+    user :: Text,+    number :: Int+  }+  deriving (Show, Eq, Generic)+  deriving (FromJSON)++data Versions = Versions+  { normal :: [Text],+    unpreferred :: [Text],+    deprecated :: [Text]+  }+  deriving (Show, Eq, Generic)++instance FromJSON Versions where+  parseJSON = withObject "versions" $ \o -> do+    let withDefault = fmap (fromMaybe [])+    normal <- withDefault (o .:? "normal-version")+    unpreferred <- withDefault (o .:? "unprefereed-version")+    deprecated <- withDefault (o .:? "deprecated-version")+    pure Versions {..}++data Cabal++instance Accept Cabal where+  contentType _ = "text" // "plain" /: ("charset", "utf-8")++instance MimeUnrender Cabal GenericPackageDescription where+  mimeUnrender _ f = r+    where+      res' = parseGenericPackageDescription $ toStrict f+      (_, res) = runParseResult res'+      showErrors es =+        "cabal file parse failed with the following errors:\n"+          <> unlines (map (showPError "") es)+      r = case res of+        Left (_, es') -> Left $ showErrors $ toList es'+        Right desc -> Right desc++data CabalFile++instance HasClient m api => HasClient m (CabalFile :> api) where+  type Client m (CabalFile :> api) = Package -> Client m api++  clientWithRoute pm Proxy req = \p@Package {..} ->+    clientWithRoute pm (Proxy @api) $+      req+        & appendToPath (toQueryParam p)+        & appendToPath (packageName <> ".cabal")++  hoistClientMonad pm Proxy f cl = hoistClientMonad pm (Proxy @api) f . cl++-----------------------------------------------------------+-- Servant API Types++type GetPackages = "packages" :> Get '[JSON0] [Package]++type GetVersions = "package" :> Capture "package" Package :> "preferred" :> Get '[JSON0] Versions++type GetRevisions = "package" :> Capture "package" Package :> "revisions" :> Get '[JSON0] [Revision]++type GetCabalFile = "package" :> CabalFile :> Get '[Cabal] GenericPackageDescription++type GetCabalFile' = "package" :> Capture "package" Package :> "revision" :> Capture "revision" Int :> Get '[Cabal] GenericPackageDescription++type HackageAPI =+  GetPackages+    :<|> GetVersions+    :<|> GetRevisions+    :<|> GetCabalFile+    :<|> GetCabalFile'
+ test/Spec.hs view
@@ -0,0 +1,30 @@+{-# LANGUAGE ExistentialQuantification #-}++module Main where++import Control.Exception+import Data.Foldable+import Distribution.Hackage.API+import Distribution.Hackage.Types+import Network.HTTP.Client.TLS+import Servant.Client++data TestCase = forall a. TestCase (ClientM a)++main :: IO ()+main = do+  manager <- newTlsManager+  let testCases =+        [ TestCase getPackages,+          TestCase $ getCabalFile (Package "Cabal" Default),+          TestCase $ getCabalFile' (Package "Cabal" Default) 0,+          TestCase $ getVersions (Package "Cabal" Default),+          TestCase $ getRevisions (Package "Cabal" Default)+        ]+  traverse_ (checkRun manager) testCases++check :: (Exception a) => Either a b -> IO ()+check (Left e) = throwIO e+check (Right _) = pure ()++checkRun manager (TestCase m) = runClient manager m >>= check