{-# LANGUAGE DeriveGeneric #-}{-# LANGUAGE FlexibleContexts #-}{-# LANGUAGE OverloadedStrings #-}{-# LANGUAGE ScopedTypeVariables #-}{-# LANGUAGE NoImplicitPrelude #-}module HWM.Runtime.Files ( readYaml, rewrite_, statusM, aesonYAMLOptions, select, addHash, forbidOverride, cleanRelativePath, aesonYAMLOptionsAdvanced, genSignature, Signature, getFileSignature, prepareDir, syncFile, rewriteMaybe_, getLocalBinDir, warnBindDir, )whereimport Control.Exception (tryJust)import Control.Monad.Error.Class (MonadError (..))import qualified Crypto.Hash.SHA256 as SHA256import Data.Aeson ( FromJSON (..), Object, Options (..), ToJSON (..), Value (..), defaultOptions, )import Data.ByteString (readFile, writeFile)import qualified Data.ByteString.Base16 as Base16import Data.Char (isUpper, toLower)import Data.List (elemIndex, stripPrefix)import Data.Map (lookup)import Data.Text (toTitle)import qualified Data.Text as Timport qualified Data.Text.Encoding as Timport qualified Data.Text.IO as TIOimport Data.Yaml (decodeThrow)import Data.Yaml.Pretty (defConfig, encodePretty, setConfCompare, setConfDropNull)import HWM.Core.Formatting (Format (..), Status (..))import HWM.Core.Result (Issue, MonadIssue (injectIssue))import Relude hiding (readFile, writeFile)import System.Directory (createDirectoryIfMissing, doesFileExist, getHomeDirectory)import System.FilePath (dropTrailingPathSeparator, joinPath, splitDirectories, splitSearchPath, (</>))data Signature = Signed Text | Unsigned deriving (Ord, Show)instance Eq Signature where (Signed hash1) == (Signed hash2) = hash1 == hash2 _ == _ = FalsegenSignature :: [Text] -> SignaturegenSignature txt = let hashInput = T.encodeUtf8 (T.intercalate ":" txt) hashBytes = SHA256.hash hashInput in Signed (T.decodeUtf8 (Base16.encode hashBytes))instance Format Signature where format (Signed hash) = "# hash: " <> hash <> "\n" format Unsigned = ""printException :: SomeException -> StringprintException = showsafeIO :: IO a -> IO (Either String a)safeIO = tryJust (Just . printException)safeRead :: (MonadIO m) => FilePath -> m (Either String ByteString)safeRead = liftIO . safeIO . readFilesafeWrite :: (MonadIO m) => FilePath -> ByteString -> m (Either String ())safeWrite file content = liftIO $ safeIO (writeFile file content)serializeYaml :: (ToJSON a) => a -> ByteStringserializeYaml = encodePretty $ setConfDropNull True $ setConfCompare compareFields defConfigdata Yaml t = Yaml { getData :: t, rawValue :: Object } deriving (Generic)instance (FromJSON t) => FromJSON (Yaml t) where parseJSON v = Yaml <$> parseJSON v <*> parseJSON vinstance (ToJSON t) => ToJSON (Yaml t) where toJSON (Yaml t v) = Object (toObject (toJSON t) <> v)toObject :: Value -> ObjecttoObject (Object x) = xtoObject _ = memptymapYaml :: (Functor m) => (Maybe t -> m t) -> Maybe (Yaml t) -> m (Yaml t)mapYaml f (Just (Yaml v props)) = (`Yaml` props) <$> f (Just v)mapYaml f Nothing = (`Yaml` mempty) <$> f NothingfromEither :: (MonadError Issue m, FromJSON b, MonadIO m) => Either a ByteString -> m (Maybe b)fromEither = either (const $ pure Nothing) (fmap Just . liftIO . decodeThrow)withThrow :: (MonadError Issue m) => m (Either String a) -> m awithThrow x = x >>= either (throwError . fromString) purerewrite_ :: (MonadError Issue m, MonadIO m, FromJSON t, ToJSON t) => FilePath -> (Maybe t -> m t) -> m Statusrewrite_ pkg f = do prevYaml <- safeRead pkg >>= fromEither nextYaml <- mapYaml f prevYaml let same = Just (toJSON nextYaml) == (toJSON <$> prevYaml) if same then pure Checked else withThrow (safeWrite pkg (serializeYaml nextYaml)) $> UpdatedrewriteMaybe_ :: (MonadError Issue m, MonadIO m, FromJSON t, ToJSON t) => FilePath -> (Maybe t -> m (Maybe t)) -> m StatusrewriteMaybe_ pkg f = do prevYaml <- safeRead pkg >>= fromEither maybeNext <- f (getData <$> prevYaml) case maybeNext of Nothing -> pure Checked -- nothing to change, so we consider it checked Just next -> do nextYaml <- mapYaml (const (pure next)) prevYaml let same = Just (toJSON nextYaml) == (toJSON <$> prevYaml) if same then pure Checked else withThrow (safeWrite pkg (serializeYaml nextYaml)) $> UpdatedstatusM :: (MonadIO m) => FilePath -> m t -> m StatusstatusM pkg m = do before <- safeRead pkg _ <- m after <- safeRead pkg pure (if before == after then Checked else Updated)readYaml :: (MonadError Issue m, MonadIO m, FromJSON a) => FilePath -> m areadYaml = withThrow . safeRead >=> (liftIO . decodeThrow)fields :: [Text]fields = map toTitle [ "name", "version", "github", "license", "author", "category", "synopsis", "maintainer", "homepage", "copyright", "license-file", "description", "bounds", "ghc", "resolver", "packages", "workspace", "builds", "extra-source-files", "data-files", "main", "source-dirs", "ghc-options", "dependencies", "library", "executables", "include", "exclude", "allow-newer", "save-hackage-creds", "extra-deps", "stackYaml", "components", "path", "component" ]toPriority :: Text -> InttoPriority = fromMaybe (length fields) . (`elemIndex` fields)mapTuple :: (a -> b) -> (b -> b -> c) -> a -> a -> cmapTuple f g a b = g (f a) (f b)compareFields :: Text -> Text -> OrderingcompareFields = mapTuple toTitle (mapTuple toPriority compare <> compare)toKebabCase :: String -> StringtoKebabCase = concatMap toKebab where toKebab x | isUpper x = ['-', toLower x] | otherwise = [x]aesonYAMLOptions :: OptionsaesonYAMLOptions = defaultOptions {fieldLabelModifier = toKebabCase . fieldLabelModifier defaultOptions, omitNothingFields = True}aesonYAMLOptionsAdvanced :: String -> OptionsaesonYAMLOptionsAdvanced prefix = defaultOptions {fieldLabelModifier = toKebabCase . stripFieldNamespace prefix . fieldLabelModifier defaultOptions, omitNothingFields = True}dropPrefix :: String -> String -> StringdropPrefix name = drop (length name)stripFieldNamespace :: String -> String -> StringstripFieldNamespace prefix = __uncapitalize . dropPrefix prefix where __uncapitalize [] = [] __uncapitalize (x : xs) = toLower x : xsselect :: (MonadError Issue m, Format t, Ord t) => Text -> t -> Map t a -> m aselect e k = maybe (throwError $ fromString $ "Unknown " <> toString e <> ": " <> toString (format k) <> "!") pure . lookup kaddHash :: (MonadIO m) => FilePath -> Signature -> m ()addHash filePath (Signed hash) = do content <- liftIO $ T.decodeUtf8 <$> readFileBS filePath let contentWithHash = "# hash: " <> hash <> "\n" <> content liftIO $ writeFileBS filePath (T.encodeUtf8 contentWithHash)addHash _ Unsigned = pure ()getFileSignature :: (MonadIO m) => FilePath -> m SignaturegetFileSignature filePath = do content <- liftIO $ T.decodeUtf8 <$> readFileBS filePath case T.lines content of (firstLine : _) -> case T.stripPrefix "# hash: " firstLine of Just hash -> pure (Signed hash) Nothing -> pure Unsigned [] -> pure UnsignedforbidOverride :: (MonadIO m, MonadError e m, IsString e) => FilePath -> m ()forbidOverride path = do exists <- liftIO $ doesFileExist path when exists $ throwError $ fromString $ "File \"" <> path <> "\" already exists!"cleanRelativePath :: Maybe String -> Maybe StringcleanRelativePath Nothing = NothingcleanRelativePath (Just "") = NothingcleanRelativePath (Just "./") = NothingcleanRelativePath (Just ".") = NothingcleanRelativePath (Just name) = Just $ joinPath $ splitDirectories $ fromMaybe name (stripPrefix "./" name)prepareDir :: (MonadIO m) => FilePath -> m ()prepareDir dir = liftIO $ createDirectoryIfMissing True dirsyncFile :: (MonadIO m) => FilePath -> Text -> m StatussyncFile path newFile = do exist <- liftIO $ doesFileExist path old <- if exist then Just <$> liftIO (TIO.readFile path) else pure Nothing if old == Just newFile then pure Checked else liftIO $ TIO.writeFile path newFile $> UpdatedgetLocalBinDir :: (MonadIssue m, MonadIO m) => m FilePathgetLocalBinDir = do home <- liftIO getHomeDirectory let dir = home </> ".local" </> "bin" liftIO $ createDirectoryIfMissing True dir pure dirwarnBindDir :: (MonadIssue m, MonadIO m) => FilePath -> m ()warnBindDir dir = do pathStr <- concatMap splitSearchPath . maybeToList <$> liftIO (lookupEnv "PATH") let pathDirs = map dropTrailingPathSeparator pathStr unless (dropTrailingPathSeparator dir `elem` pathDirs) $ do injectIssue (fromString $ "Directory " <> dir <> " is not on your $PATH. Executables installed here will not be globally available.")