From dc9a86a603fbf253e7147848a2088317bdeb12f0 Mon Sep 17 00:00:00 2001 From: b0oh <> Date: Mon, 16 Sep 2024 18:01:12 +0700 Subject: [PATCH] Check if config already exists for hbs2-sync init --- hbs2-sync/app/Main.hs | 3 +-- hbs2-sync/src/HBS2/Sync/Internal.hs | 35 ++++++++++++++++++++++++++--- 2 files changed, 33 insertions(+), 5 deletions(-) diff --git a/hbs2-sync/app/Main.hs b/hbs2-sync/app/Main.hs index bf1936c1..f6bdd270 100644 --- a/hbs2-sync/app/Main.hs +++ b/hbs2-sync/app/Main.hs @@ -51,11 +51,10 @@ main = do _ -> display cli dir <- pwd - here <- liftIO $ doesFileExist (dir ".hbs2-sync/config") + here <- liftIO $ doesFileExist (configPath dir) void $ runSyncApp $ recover $ do when here $ runM dict do void $ evalTop [ mkList [mkSym "dir", mkStr dir] ] run dict cli - diff --git a/hbs2-sync/src/HBS2/Sync/Internal.hs b/hbs2-sync/src/HBS2/Sync/Internal.hs index dc983c88..780fd4b3 100644 --- a/hbs2-sync/src/HBS2/Sync/Internal.hs +++ b/hbs2-sync/src/HBS2/Sync/Internal.hs @@ -1,5 +1,5 @@ module HBS2.Sync.Internal - ( syncEntries + ( configPath, syncEntries ) where import HBS2.Sync.Prelude @@ -34,10 +34,35 @@ import Data.Ord import Streaming.Prelude qualified as S +data ConfigException + = ConfigAlreadyExists String + deriving (Show) + +instance Exception ConfigException + +configPath :: FilePath -> FilePath +configPath directory = + directory ".hbs2-sync/config" + +findConfig :: (MonadIO m) => m (Maybe FilePath) +findConfig = + findConfig' =<< pwd + where + findConfig' level = do + let path = configPath level + exists <- liftIO $ doesFileExist path + if exists + then return $ Just path + else + let parent = takeDirectory level + in if parent == level -- we've reached the root directory + then return Nothing + else findConfig' parent syncEntries :: forall c m . ( MonadUnliftIO m , IsContext c , Exception (BadFormException c) + , Exception ConfigException , HasClientAPI PeerAPI UNIX m , HasClientAPI RefChanAPI UNIX m , HasClientAPI StorageAPI UNIX m @@ -63,6 +88,8 @@ syncEntries = do authorKey <- fromStringMay @(PubKey 'Sign HBS2Basic) authorString & orThrowUser "author not found" readerKey <- fromStringMay @(PubKey 'Encrypt HBS2Basic) readerString & orThrowUser "reader not found" + findConfig >>= maybe (pure ()) (throwIO . ConfigAlreadyExists) + peerApi <- getClientAPI @PeerAPI @UNIX rchanApi <- getClientAPI @RefChanAPI @UNIX storage <- getStorage @@ -103,10 +130,12 @@ syncEntries = do ] let config = unlines $ map (show . pretty) configForms display config - let path = ".hbs-sync/config" + liftIO $ do + path <- configPath <$> pwd createDirectoryIfMissing True $ takeDirectory path writeFile path config + pure () _ -> do @@ -140,7 +169,7 @@ syncEntries = do Nothing -> Just (mempty & set dirSyncPath (Just d)) Just x -> Just (x & set dirSyncPath (Just d)) - ins <- try @_ @IOError (liftIO $ readFile (d ".hbs2-sync/config")) + ins <- try @_ @IOError (liftIO $ readFile (configPath d)) <&> fromRight mempty <&> parseTop <&> either mempty (fmap fixContext)