{-# LANGUAGE DataKinds #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE TupleSections #-}
{-# LANGUAGE TypeApplications #-}
module Aura.Cache
(
Cache(..)
, cacheContents
, defaultPackageCache
, cacheMatches
, pkgsInCache
) where
import Aura.Settings
import Aura.Types
import Data.Generics.Product (field)
import Data.Set.NonEmpty (NESet)
import qualified Data.Set.NonEmpty as NES
import RIO
import qualified RIO.Map as M
import qualified RIO.Set as S
import qualified RIO.Text as T
import System.Path
(Absolute, Path, fromAbsoluteFilePath, toFilePath, (</>))
import System.Path.IO (getDirectoryContents)
newtype Cache = Cache { _cache :: Map SimplePkg PackagePath }
defaultPackageCache :: Path Absolute
defaultPackageCache = fromAbsoluteFilePath "/var/cache/pacman/pkg/"
cache :: [PackagePath] -> Cache
cache = Cache . M.fromList . mapMaybe (\p -> (,p) <$> simplepkg p)
cacheContents :: Path Absolute -> IO Cache
cacheContents pth = cache . map (PackagePath . (pth </>)) <$> getDirectoryContents pth
pkgsInCache :: Settings -> NESet PkgName -> IO (Set PkgName)
pkgsInCache ss ps = do
c <- cacheContents . either id id . cachePathOf $ commonConfigOf ss
pure . S.filter (`NES.member` ps) . S.map (^. field @"name") . M.keysSet $ _cache c
cacheMatches :: Settings -> Text -> IO [PackagePath]
cacheMatches ss input = do
c <- cacheContents . either id id . cachePathOf $ commonConfigOf ss
pure . filter (T.isInfixOf input . T.pack . toFilePath . path) . M.elems $ _cache c