diff --git a/libs/api-bot/src/Network/Wire/Bot/Assert.hs b/libs/api-bot/src/Network/Wire/Bot/Assert.hs index 138c2fd4ab5..ed40c15e955 100644 --- a/libs/api-bot/src/Network/Wire/Bot/Assert.hs +++ b/libs/api-bot/src/Network/Wire/Bot/Assert.hs @@ -63,8 +63,8 @@ awaitOtrMessage :: m (Maybe (ConvEvent OtrMessage)) awaitOtrMessage c (from, fc) (to, tc) = awaitEvent to TConvOtrMessageAdd assertion >>= \case - Just (EOtrMessage m) -> return (Just m) - _ -> return Nothing + Just (EOtrMessage m) -> pure (Just m) + _ -> pure Nothing where assertion (EOtrMessage evt) = let e = convEvtData evt @@ -83,7 +83,7 @@ assertMembersJoined :: -- | Users who have (presumably) joined Maybe (ConvEvent SimpleMembers) -> m () -assertMembersJoined _ Nothing = return () +assertMembersJoined _ Nothing = pure () assertMembersJoined bs (Just e) = forM_ bs $ \b -> assertEvent b TConvMemberJoin memAdd where @@ -99,7 +99,7 @@ assertMembersLeft :: -- | Users who have (presumably) left Maybe (ConvEvent UserIdList) -> m () -assertMembersLeft _ Nothing = return () +assertMembersLeft _ Nothing = pure () assertMembersLeft bs (Just e) = forM_ bs $ \b -> assertEvent b TConvMemberLeave memRem where diff --git a/libs/api-bot/src/Network/Wire/Bot/Cache.hs b/libs/api-bot/src/Network/Wire/Bot/Cache.hs index 612a7c9eb17..1a8b41d2cd5 100644 --- a/libs/api-bot/src/Network/Wire/Bot/Cache.hs +++ b/libs/api-bot/src/Network/Wire/Bot/Cache.hs @@ -58,7 +58,7 @@ fromFile logger gen domain path = do triples <- map (Text.splitOn ",") . Text.lines <$> Text.readFile path shuffled <- V.toList <$> uniformShuffle (V.fromList triples) gen c <- newIORef =<< foldM (toUser logger domain) [] shuffled - return (Cache c) + pure (Cache c) empty :: IO Cache empty = Cache <$> newIORef [] @@ -82,7 +82,7 @@ toUser _ domain acc [i, e, p] = do let ie = error "Cache.toUser: invalid email" let ui = fromMaybe iu . fromByteString . encodeUtf8 . Text.toStrict . Text.strip $ i let em = fromMaybe ie . parseEmail . Text.toStrict . Text.strip $ e - return . (: acc) $ + pure . (: acc) $ CachedUser pw User @@ -103,4 +103,4 @@ toUser _ domain acc [i, e, p] = do } toUser g _ acc entry = do warn g $ msg (val "invalid entry: " +++ show entry) - return acc + pure acc diff --git a/libs/api-bot/src/Network/Wire/Bot/Clients.hs b/libs/api-bot/src/Network/Wire/Bot/Clients.hs index 707b02ce90a..80c22247d2b 100644 --- a/libs/api-bot/src/Network/Wire/Bot/Clients.hs +++ b/libs/api-bot/src/Network/Wire/Bot/Clients.hs @@ -57,7 +57,7 @@ addMembers self c uu = -- TODO: Move / inline to Network.Wire.Bot.Crypto and remove this module foldSessions :: MonadIO m => Clients -> ConvId -> a -> (UserId -> ClientId -> Session -> a -> m a) -> m a foldSessions self c a f = - foldrM fun a =<< Map.findWithDefault Set.empty c <$> liftIO (readTVarIO (members self)) + foldrM fun a . Map.findWithDefault Set.empty c =<< liftIO (readTVarIO (members self)) where fun u acc1 = do cm <- Map.findWithDefault Map.empty u . clients <$> liftIO (readTVarIO (sessions self)) @@ -66,4 +66,4 @@ foldSessions self c a f = lookupSession :: MonadIO m => Clients -> UserId -> ClientId -> m (Maybe Session) lookupSession self u d = do s <- liftIO $ readTVarIO (sessions self) - return $ Map.lookup u (clients s) >>= Map.lookup d + pure $ Map.lookup u (clients s) >>= Map.lookup d diff --git a/libs/api-bot/src/Network/Wire/Bot/Crypto.hs b/libs/api-bot/src/Network/Wire/Bot/Crypto.hs index 3e7ca8b526b..84e037529b5 100644 --- a/libs/api-bot/src/Network/Wire/Bot/Crypto.hs +++ b/libs/api-bot/src/Network/Wire/Bot/Crypto.hs @@ -95,7 +95,7 @@ clientInitSession cl uid = do k <- decodePrekey c let i = mkSID uid (prekeyClient c) s <- liftIO $ unwrap =<< CBox.sessionFromPrekey b i k - return (prekeyClient c, s) + pure (prekeyClient c, s) -- | Initialise an OTR session between the given 'BotClient' and the sender of -- the given OTR message. @@ -116,12 +116,12 @@ encrypt cl cnv val = fmap (OtrRecipients . UserClientMap) . foldSessions (botClientSessions cl) cnv Map.empty $ \u c s rcps -> if botClientId cl == c - then return rcps + then pure rcps else liftIO $ do ciphertext <- do bs <- CBox.encrypt s val >>= unwrap >>= CBox.copyBytes - return $! decodeUtf8 $! B64.encode bs - return $ Map.insertWith Map.union u (Map.singleton c ciphertext) rcps + pure $! decodeUtf8 $! B64.encode bs + pure $ Map.insertWith Map.union u (Map.singleton c ciphertext) rcps -- | Decrypt an OTR message received from a given user and client. decrypt :: BotClient -> UserId -> ClientId -> ByteString -> BotSession ByteString @@ -172,7 +172,7 @@ encryptSymmetric clt (SymmetricKeys ekey mkey) msg = liftIO $ do iv <- randomBytes (botClientBox clt) 16 let ciphertext = iv <> cbcEncrypt aes (aesIV iv) (padPKCS7 msg) let mac = hmac (toByteString' mkey) ciphertext :: HMAC SHA256 - return $ convert mac <> ciphertext + pure $ convert mac <> ciphertext decryptSymmetric :: MonadIO m => BotClient -> SymmetricKeys -> Ciphertext -> m Plaintext decryptSymmetric _ (SymmetricKeys ekey mkey) msg = liftIO $ do @@ -184,7 +184,7 @@ decryptSymmetric _ (SymmetricKeys ekey mkey) msg = liftIO $ do throwM $ RequirementFailed "Bad MAC" let (iv, dat) = BS.splitAt 16 ciphertext - return $ unpadPKCS7 $ cbcDecrypt aes (aesIV iv) dat + pure $ unpadPKCS7 $ cbcDecrypt aes (aesIV iv) dat ----------------------------------------------------------------------------- -- Helpers diff --git a/libs/api-bot/src/Network/Wire/Bot/Crypto/Glue.hs b/libs/api-bot/src/Network/Wire/Bot/Crypto/Glue.hs index 1905fe82b1e..c0eec265b01 100644 --- a/libs/api-bot/src/Network/Wire/Bot/Crypto/Glue.hs +++ b/libs/api-bot/src/Network/Wire/Bot/Crypto/Glue.hs @@ -1,5 +1,3 @@ -{-# LANGUAGE LambdaCase #-} - -- This file is part of the Wire Server implementation. -- -- Copyright (C) 2022 Wire Swiss GmbH @@ -67,7 +65,7 @@ randomBytes :: MonadIO m => Box -> Word32 -> m ByteString randomBytes b n = liftIO $ CBox.randomBytes b n >>= unwrap >>= CBox.copyBytes unwrap :: (Show a, MonadThrow m) => CBox.Result a -> m a -unwrap (CBox.Success a) = return a +unwrap (CBox.Success a) = pure a unwrap other = throwM $ userError (show other) getBoxDir :: UserId -> Maybe Text -> IO FilePath @@ -75,4 +73,4 @@ getBoxDir uid label = do tmp <- getTemporaryDirectory let usrDir = show (toUUID uid) let cltDir = maybe "" Text.unpack label - return $ tmp "wire-bot" usrDir cltDir + pure $ tmp "wire-bot" usrDir cltDir diff --git a/libs/api-bot/src/Network/Wire/Bot/Email.hs b/libs/api-bot/src/Network/Wire/Bot/Email.hs index 73406dea5be..2d5dada326a 100644 --- a/libs/api-bot/src/Network/Wire/Bot/Email.hs +++ b/libs/api-bot/src/Network/Wire/Bot/Email.hs @@ -78,7 +78,7 @@ instance Exception MailException loadMailboxConfig :: FilePath -> IO [Mailbox] loadMailboxConfig p = do cfg <- LB.readFile p - mbs <- either error return (eitherDecode' cfg) :: IO [MailboxSettings] + mbs <- either error pure (eitherDecode' cfg) :: IO [MailboxSettings] mapM newMailbox mbs newMailbox :: MailboxSettings -> IO Mailbox @@ -88,7 +88,7 @@ newMailbox s@(MailboxSettings host usr pwd conns) = connect = do c <- connectIMAPSSLWithSettings host defaultSettingsIMAPSSL login c (show usr) pwd - return c + pure c -- | Awaits activation e-mail to arrive at a mailbox with -- the designated recipient address. @@ -109,7 +109,7 @@ awaitActivationMail mbox folders from to = do let codeHdr = find ((== "x-zeta-code") . paramName) hdrs case liftM2 (,) keyHdr codeHdr of Just (k, c) -> - return $ + pure $ ( ActivationKey $ Ascii.unsafeFromText $ paramValue k, ActivationCode $ Ascii.unsafeFromText $ paramValue c ) @@ -132,7 +132,7 @@ awaitPasswordResetMail mbox folders from to = do let codeHdr = find ((== "x-zeta-code") . paramName) hdrs case liftM2 (,) keyHdr codeHdr of Just (k, c) -> - return $ + pure $ ( PasswordResetKey $ Ascii.unsafeFromText $ paramValue k, PasswordResetCode $ Ascii.unsafeFromText $ paramValue c ) @@ -153,7 +153,7 @@ awaitInvitationMail mbox folders from to = do let hdrs = mime_val_headers msg let invHdr = find ((== "x-zeta-code") . paramName) hdrs case invHdr of - Just i -> return . read . T.unpack $ paramValue i + Just i -> pure . read . T.unpack $ paramValue i Nothing -> throwIO MissingEmailHeaders awaitMail :: @@ -176,7 +176,7 @@ awaitMail mbox folders from to purpose = go 0 case msgs of [] | t >= timeout -> throwIO EmailTimeout [] -> threadDelay sleep >> go (t + sleep) - (m : ms) -> return (m :| ms) + (m : ms) -> pure (m :| ms) fetchMail :: Mailbox -> @@ -192,7 +192,7 @@ fetchMail :: fetchMail mbox folders from to purpose = withResource (mailboxPool mbox) $ \c -> do msgIds <- concat <$> forM folders (searchMail c) msgs <- mapM (fetch c) msgIds - return $ map (parseMIMEMessage . T.decodeLatin1) msgs + pure $ map (parseMIMEMessage . T.decodeLatin1) msgs where searchMail c folder = do select c folder diff --git a/libs/api-bot/src/Network/Wire/Bot/Monad.hs b/libs/api-bot/src/Network/Wire/Bot/Monad.hs index 04dcd73c4fd..6e36bc8efb9 100644 --- a/libs/api-bot/src/Network/Wire/Bot/Monad.hs +++ b/libs/api-bot/src/Network/Wire/Bot/Monad.hs @@ -158,7 +158,7 @@ newBotNetEnv manager logger o = do gen <- MWC.createSystemRandom let domain = setBotNetFederationDomain o usr <- maybe Cache.empty (Cache.fromFile logger gen domain) (setBotNetUsersFile o) - mbx <- maybe (return []) loadMailboxConfig (setBotNetMailboxConfig o) + mbx <- maybe (pure []) loadMailboxConfig (setBotNetMailboxConfig o) met <- initMetrics let srv = Server @@ -169,7 +169,7 @@ newBotNetEnv manager logger o = do serverSSL = setBotNetApiSSL o, serverManager = manager } - return + pure $! BotNetEnv { botNetGen = gen, botNetMailboxes = mbx, @@ -192,7 +192,7 @@ initMetrics = do m <- Metrics.metrics forM_ counters $ \c -> Metrics.counterGet c m forM_ gauges $ \g -> Metrics.gaugeGet g m - return m + pure m where counters = Metrics.assertionsTotal : @@ -403,7 +403,7 @@ addBotClient self cty label = do cid <- clientId <$> runBotSession self (registerClient nc) clt <- BotClient cid label box <$> liftIO Clients.empty liftIO . atomically $ modifyTVar' (botClients self) (clt :) - return clt + pure clt -- TODO: withBotClient :: MonadBotNet m => Bot -> ClientType -> Maybe Text -> (BotClient -> m a) -> m a @@ -455,7 +455,7 @@ newBot tag = liftBotNet $ do bot <- mkBot tag user pw -- TODO: addBotClient? incrBotsCreatedNew - return bot + pure bot -- | Obtain a "cached" 'Bot' based on an existing user identity. The same -- bot will never be returned again by 'cachedBot'. @@ -466,7 +466,7 @@ cachedBot t = liftBotNet $ do CachedUser p u <- BotNet (asks botNetUsers) >>= Cache.get bot <- mkBot t (tagged t u) p incrBotsCreatedCached - return bot + pure bot -- | Wait for the Bot's assertions to finish (through matching -- an event or through timeout) before killing it (see 'killBot'). @@ -551,7 +551,7 @@ whenAsserts ma = liftBotNet $ do -- | Wait for the Bot's assertion queue to become empty. awaitAssertions :: MonadBotNet m => Bot -> m () awaitAssertions bot = whenAsserts $ do - n <- liftIO . atomically $ readTVar (botAssertCount bot) + n <- liftIO (readTVarIO (botAssertCount bot)) unless (n <= 0) $ do liftIO $ threadDelay 1000000 awaitAssertions bot @@ -560,20 +560,20 @@ awaitAssertions bot = whenAsserts $ do -- enabled or not. If the requirement fails, a 'RequirementFailed' exception -- is thrown. require :: MonadThrow m => Bool -> Text -> m () -require True _ = return () +require True _ = pure () require False m = throwM $ RequirementFailed m -- | Require a 'Maybe a' to be 'Just a', regardless of whether assertions are -- enabled or not. If it is 'Nothing' a 'RequirementFailed' exception is thrown. requireMaybe :: MonadThrow m => Maybe a -> Text -> m a requireMaybe Nothing m = throwM $ RequirementFailed m -requireMaybe (Just a) _ = return a +requireMaybe (Just a) _ = pure a -- | Require a 'Either e a' to be 'Right a', regardless of whether assertions are -- enabled or not. If it is 'Left e 'RequirementFailed' exception is thrown. requireRight :: (Show e, MonadThrow m) => Either e a -> m a requireRight (Left e) = throwM $ RequirementFailed (pack $ show e) -requireRight (Right a) = return a +requireRight (Right a) = pure a -- TODO: change argument order to match 'assertEqual' from tasty-hunit assertEqual :: (HasCallStack, MonadBotNet m, Show a, Eq a) => a -> a -> Text -> m () @@ -630,11 +630,11 @@ scheduleAssert bot typ f out = whenAsserts $ do r <- liftIO . atomically $ do n <- readTVar (botAssertCount bot) if n >= botMaxAsserts (botSettings bot) - then return False + then pure False else do writeTQueue (botAsserts bot) (EventAssertion typ t f out callStack) writeTVar (botAssertCount bot) (n + 1) - return True + pure True unless r . liftBotNet $ do incrAssertFailed runBotSession bot . log Error . msg $ @@ -675,13 +675,13 @@ try ma = do Left e -> do liftBotNet $ log Error . msg $ show e incrExceptionsTotal - return $ Left e - Right a -> return $ Right a + pure $ Left e + Right a -> pure $ Right a where handlers = - [ Handler $ \e -> return . Left $ BotNetFailure e, - Handler $ \e -> return . Left $ HttpFailure e, - Handler $ \e -> return . Left $ ClientFailure e + [ Handler $ \e -> pure . Left $ BotNetFailure e, + Handler $ \e -> pure . Left $ HttpFailure e, + Handler $ \e -> pure . Left $ ClientFailure e ] ------------------------------------------------------------------------------- @@ -692,7 +692,7 @@ mkBot tag user pw = do log Info $ botLogFields (userId user) tag . msg (val "Login") let ident = fromMaybe (error "No email") (userEmail user) let cred = PasswordLogin (LoginByEmail ident) pw Nothing Nothing - auth <- login cred >>= maybe (throwM LoginFailed) return + auth <- login cred >>= maybe (throwM LoginFailed) pure aref <- nextAuthRefresh auth env <- BotNet ask bot <- @@ -715,7 +715,7 @@ mkBot tag user pw = do when (botNetAssert env) $ writeIORef (botAssertThread bot) . Just =<< async (assert bot env) incrBotsAlive - return bot + pure bot connectPush :: Bot -> BotNetEnv -> IO (Async ()) connectPush bot e = runBotNet e . runBotSession bot $ do @@ -775,7 +775,7 @@ heartbeat bot e = forever $ do <> "\nAssertion was created at: " <> pack (prettyCallStack stack) -- Re-establish the push connection, if it died - push <- maybe (return Nothing) poll =<< readIORef (botPushThread bot) + push <- maybe (pure Nothing) poll =<< readIORef (botPushThread bot) case push of Just x -> do case x of @@ -783,7 +783,7 @@ heartbeat bot e = forever $ do Right _ -> botLog l bot Warn $ msg $ val "Unexpected exit of push thread" a <- connectPush bot e writeIORef (botPushThread bot) (Just a) - Nothing -> return () + Nothing -> pure () assert :: Bot -> BotNetEnv -> IO a assert bot e = forever $ do @@ -807,7 +807,7 @@ matchAssertion bot a@(EventAssertion _ _ f out _) = do modifyTVar' (botAssertCount bot) (subtract 1) incrEventsAckd bot (eventType ev) Nothing -> modifyTVar' (botBacklog bot) (a :) - return found + pure found where go (events, found) (et, ev) | isNothing found && f ev = (events, Just ev) @@ -833,7 +833,7 @@ gcEvents bot now = do when (numDel > 0) $ do writeTVar (botEvents bot) (num - numDel, keep) mapM_ (incrEventsIgnd bot . eventType . snd) del - return $ fmap snd del + pure $ fmap snd del gcBacklog :: Bot -> UTCTime -> STM [EventAssertion] gcBacklog bot now = do @@ -847,12 +847,12 @@ gcBacklog bot now = do forM_ del $ \(EventAssertion typ _ _ out _) -> do for_ out $ flip tryPutTMVar Nothing incrEventsMssd bot typ - return del + pure del nextAuthRefresh :: MonadIO m => Auth -> m UTCTime nextAuthRefresh (Auth _ tok) = liftIO $ do now <- getCurrentTime - return $ (fromInteger (expiresIn tok) - 60) `addUTCTime` now + pure $ (fromInteger (expiresIn tok) - 60) `addUTCTime` now ------------------------------------------------------------------------------- @@ -869,7 +869,7 @@ report t s = do f = showString (unpack t) . showString "-" . showString d $ ".bot" in writeReport (dir f) r Nothing -> printReport r - return r + pure r getMetrics :: MonadBotNet m => m Metrics getMetrics = liftBotNet . BotNet $ asks botNetMetrics @@ -883,7 +883,7 @@ timed p ma = do m <- getMetrics let timeHisto = Metrics.deprecatedRequestDurationHistogram p liftIO $ Metrics.histoSubmit durationInMillis timeHisto m - return a + pure a incrAssertTotal :: MonadBotNet m => m () incrAssertTotal = getMetrics >>= liftIO . Metrics.counterIncr Metrics.assertionsTotal @@ -951,7 +951,7 @@ transferBotMetrics b = ackd <- readTVar $ botEventsAckd (botMetrics b) ignd <- readTVar $ botEventsIgnd (botMetrics b) mssd <- readTVar $ botEventsMssd (botMetrics b) - return [rcvd, ackd, ignd, mssd] + pure [rcvd, ackd, ignd, mssd] -- Update per event type counters let add (p, n) = Metrics.counterAdd n p m mapM_ add (concatMap HashMap.toList l) @@ -981,7 +981,7 @@ randUser (Email loc dom) (BotTag tag) = do pwdUuid <- nextRandom let email = Email (loc <> "+" <> tag <> "-" <> pack (toString uuid)) dom let passw = PlainTextPassword (pack (toString pwdUuid)) - return + pure ( NewUser { newUserDisplayName = Name (tag <> "-Wirebot-" <> pack (toString uuid)), newUserUUID = Nothing, @@ -1005,7 +1005,7 @@ randMailbox :: BotNet Mailbox randMailbox = do e <- BotNet ask i <- liftIO $ MWC.uniformR (0, length (botNetMailboxes e) - 1) (botNetGen e) - return $ botNetMailboxes e !! i + pure $ botNetMailboxes e !! i tagged :: BotTag -> User -> User tagged t u = u {userDisplayName = Name $ unTag t <> "-" <> fromName (userDisplayName u)} diff --git a/libs/api-bot/src/Network/Wire/Bot/Report.hs b/libs/api-bot/src/Network/Wire/Bot/Report.hs index a729ad0cd9c..9a590260064 100644 --- a/libs/api-bot/src/Network/Wire/Bot/Report.hs +++ b/libs/api-bot/src/Network/Wire/Bot/Report.hs @@ -71,19 +71,19 @@ createReport :: MonadIO m => Text -> Metrics -> SectionS -> m Report createReport t m (SectionS (Endo f)) = do d <- liftIO getCurrentTime v <- liftIO $ foldM go mempty (concatMap sectionMetrics s) - return $! Report t d s v + pure $! Report t d s v where s = f [] go (Data cs ls bs gs) metric = case metric of Counter _ p -> do v <- counterValue =<< counterGet p m - return $! Data (HashMap.insert p v cs) ls bs gs + pure $! Data (HashMap.insert p v cs) ls bs gs Gauge _ p -> do v <- gaugeValue =<< gaugeGet p m - return $! Data cs ls bs (HashMap.insert p v gs) + pure $! Data cs ls bs (HashMap.insert p v gs) Histogram _ p hi -> do v <- histoGet hi m >>= histoValue - return $! Data cs ls (HashMap.insert p v bs) gs + pure $! Data cs ls (HashMap.insert p v bs) gs ------------------------------------------------------------------------------- diff --git a/libs/api-bot/src/Network/Wire/Bot/Report/Text.hs b/libs/api-bot/src/Network/Wire/Bot/Report/Text.hs index d12a59a30ba..17afb497862 100644 --- a/libs/api-bot/src/Network/Wire/Bot/Report/Text.hs +++ b/libs/api-bot/src/Network/Wire/Bot/Report/Text.hs @@ -60,8 +60,8 @@ formatReport pretty r = pp bold <> fromText (sectionName s) <> "\n" <> pp clear <> foldMap metric (sectionMetrics s) <> "\n" - metric (Counter l p) = single l . fromString . show $ (reportCounter r p) - metric (Gauge l p) = single l . fromString . show $ (reportGauge r p) + metric (Counter l p) = single l . fromString . show $ reportCounter r p + metric (Gauge l p) = single l . fromString . show $ reportGauge r p metric (Histogram l p _) = multi l $ sort $ Map.toList (reportBucket r p) single k v = "\t" <> fromText k <> ": " <> value v <> "\n" multi k v = "\t" <> subsection k <> "\n" <> foldMap pair v diff --git a/libs/api-bot/src/Network/Wire/Bot/Settings.hs b/libs/api-bot/src/Network/Wire/Bot/Settings.hs index 823adb2697b..15d0f447b90 100644 --- a/libs/api-bot/src/Network/Wire/Bot/Settings.hs +++ b/libs/api-bot/src/Network/Wire/Bot/Settings.hs @@ -147,7 +147,7 @@ usersFileOption = \ containing a list of ALREADY EXISTING users with the columns: \ \ User-Id,Email,Password" -usersFederationDomain :: Parser (Domain) +usersFederationDomain :: Parser Domain usersFederationDomain = domainOption $ long "users-federation-domain" @@ -275,7 +275,7 @@ assertTimeoutOption = greater :: (Integral a, Show a) => a -> a -> ReadM a greater n a | a <= n = readerError ("must be > " ++ show n) - | otherwise = return a + | otherwise = pure a bsOption :: Mod OptionFields String -> Parser ByteString bsOption = fmap pack . strOption diff --git a/libs/api-client/src/Network/Wire/Client/API/Asset.hs b/libs/api-client/src/Network/Wire/Client/API/Asset.hs index 9fc48d83188..e68c7719472 100644 --- a/libs/api-client/src/Network/Wire/Client/API/Asset.hs +++ b/libs/api-client/src/Network/Wire/Client/API/Asset.hs @@ -69,8 +69,8 @@ getAsset :: MonadSession m => AssetKey -> Maybe AssetToken -> m (Maybe AssetData getAsset key tok = do rs <- sessionRequest req rsc consumeBody liftIO $ case statusCode rs of - 200 -> maybe (unexpected rs "getAsset: missing body") (return . Just) (responseBody rs) - 404 -> return Nothing + 200 -> maybe (unexpected rs "getAsset: missing body") (pure . Just) (responseBody rs) + 404 -> pure Nothing _ -> unexpected rs "getAsset: response code" where req = diff --git a/libs/api-client/src/Network/Wire/Client/API/Auth.hs b/libs/api-client/src/Network/Wire/Client/API/Auth.hs index 12c6c7816eb..aaaa54b6e47 100644 --- a/libs/api-client/src/Network/Wire/Client/API/Auth.hs +++ b/libs/api-client/src/Network/Wire/Client/API/Auth.hs @@ -110,17 +110,17 @@ tokenResponse :: IO (Maybe Auth) tokenResponse rq rs ck | statusCode rs == 200 = mkAuth - | statusCode rs == 403 = return Nothing + | statusCode rs == 403 = pure Nothing | otherwise = unexpected rs "tokenResponse: status code" where mkAuth = do cok <- mkCookie $ parseSetCookie <$> getHeader "Set-Cookie" rs tok <- responseJsonThrow (ParseError . pack) rs - return . Just $ Auth cok tok - mkCookie Nothing = maybe (unexpected rs "missing set-cookie") return ck + pure . Just $ Auth cok tok + mkCookie Nothing = maybe (unexpected rs "missing set-cookie") pure ck mkCookie (Just hdr) = do now <- getCurrentTime case generateCookie hdr rq now True of - Just cok | cookie_name cok == "zuid" -> return $ AuthCookie cok + Just cok | cookie_name cok == "zuid" -> pure $ AuthCookie cok Just (cookie_name -> cok) -> unexpected rs $ "unknown cookie: " <> T.decodeLatin1 cok Nothing -> unexpected rs "invalid cookie" diff --git a/libs/api-client/src/Network/Wire/Client/API/Client.hs b/libs/api-client/src/Network/Wire/Client/API/Client.hs index 4d436ce4798..ff41887026f 100644 --- a/libs/api-client/src/Network/Wire/Client/API/Client.hs +++ b/libs/api-client/src/Network/Wire/Client/API/Client.hs @@ -52,7 +52,7 @@ registerClient a = sessionRequest req rsc readBody rsc = status201 :| [] removeClient :: MonadSession m => ClientId -> RmClient -> m () -removeClient cid r = sessionRequest req rsc (const $ return ()) +removeClient cid r = sessionRequest req rsc (const $ pure ()) where req = method DELETE @@ -73,7 +73,7 @@ getClients = sessionRequest req rsc readBody rsc = status200 :| [] updateClient :: MonadSession m => ClientId -> UpdateClient -> m () -updateClient cid r = sessionRequest req rsc (const $ return ()) +updateClient cid r = sessionRequest req rsc (const $ pure ()) where req = method PUT diff --git a/libs/api-client/src/Network/Wire/Client/API/Conversation.hs b/libs/api-client/src/Network/Wire/Client/API/Conversation.hs index b4a2cb47173..3dc4ace781d 100644 --- a/libs/api-client/src/Network/Wire/Client/API/Conversation.hs +++ b/libs/api-client/src/Network/Wire/Client/API/Conversation.hs @@ -1,5 +1,4 @@ {-# LANGUAGE OverloadedStrings #-} -{-# LANGUAGE ViewPatterns #-} -- This file is part of the Wire Server implementation. -- @@ -72,7 +71,7 @@ addMembers cnv mems = do rs <- sessionRequest req rsc consumeBody case statusCode rs of 200 -> Just <$> responseJsonThrow (ParseError . pack) rs - 204 -> return Nothing + 204 -> pure Nothing _ -> unexpected rs "addMembers: status code" where req = @@ -90,7 +89,7 @@ removeMember cnv mem = do rs <- sessionRequest req rsc consumeBody case statusCode rs of 200 -> Just <$> responseJsonThrow (ParseError . pack) rs - 204 -> return Nothing + 204 -> pure Nothing _ -> unexpected rs "removeMember: status code" where req = @@ -102,7 +101,7 @@ removeMember cnv mem = do -- FUTUREWORK: probably should be 'Wire.API.Conversation.Member.MemberUpdate'. memberUpdate :: MonadSession m => ConvId -> MemberUpdateData -> m () -memberUpdate cnv updt = sessionRequest req rsc (const $ return ()) +memberUpdate cnv updt = sessionRequest req rsc (const $ pure ()) where req = method PUT @@ -117,7 +116,7 @@ getConv cnv = do rs <- sessionRequest req rsc consumeBody case statusCode rs of 200 -> responseJsonThrow (ParseError . pack) rs - 404 -> return Nothing + 404 -> pure Nothing _ -> unexpected rs "getConv: status code" where req = diff --git a/libs/api-client/src/Network/Wire/Client/API/Push.hs b/libs/api-client/src/Network/Wire/Client/API/Push.hs index b74419fb168..cddd7be34c0 100644 --- a/libs/api-client/src/Network/Wire/Client/API/Push.hs +++ b/libs/api-client/src/Network/Wire/Client/API/Push.hs @@ -118,7 +118,7 @@ awaitNotifications f = do putMVar latch () >> consume l c `onException` tryPutMVar latch () takeMVar latch - return worker + pure worker where params h p = ConnectionParams h p Nothing Nothing consume l c = forever (WS.receiveData c >>= forward l) `finally` close c @@ -130,7 +130,7 @@ awaitNotifications f = do Right event -> f event Left e -> Log.err l $ Log.msg ("parse-event: " ++ e) readChunk c = (\x -> if C.null x then Nothing else Just x) <$> connectionGetChunk c - writeChunk c = maybe (return ()) (connectionPut c . L.toStrict) + writeChunk c = maybe (pure ()) (connectionPut c . L.toStrict) fetchNotifications :: (MonadSession m, MonadThrow m) => @@ -156,7 +156,7 @@ lastNotification = do rs <- sessionRequest req rsc consumeBody case statusCode rs of 200 -> Just <$> responseJsonThrow (ParseError . pack) rs - 404 -> return Nothing + 404 -> pure Nothing _ -> unexpected rs "last: status code" where req = @@ -279,7 +279,7 @@ instance FromJSON Event where instance FromJSON NotifId where parseJSON = withText "notification-id" $ - maybe (fail "invalid uuid") (return . NotifId) . fromString . T.unpack + maybe (fail "invalid uuid") (pure . NotifId) . fromString . T.unpack instance FromJSON Notification where parseJSON = withObject "notification" $ \o -> @@ -293,7 +293,7 @@ instance FromJSON a => FromJSON (ConvEvent a) where <*> o .: "data" instance FromJSON NoData where - parseJSON Null = return NoData + parseJSON Null = pure NoData parseJSON _ = fail "Unexpected event data. Expecting nothing/null." instance FromJSON UserInfo where diff --git a/libs/api-client/src/Network/Wire/Client/API/User.hs b/libs/api-client/src/Network/Wire/Client/API/User.hs index 7bb4f472e67..7013d48c70c 100644 --- a/libs/api-client/src/Network/Wire/Client/API/User.hs +++ b/libs/api-client/src/Network/Wire/Client/API/User.hs @@ -64,8 +64,8 @@ registerUser u = clientRequest req rsc readBody activateKey :: (MonadClient m, MonadUnliftIO m, MonadMask m) => ActivationKey -> ActivationCode -> m Bool activateKey (ActivationKey key) (ActivationCode code) = do - status <- clientRequest req rsc (return . statusCode) - return $ status /= 404 + status <- clientRequest req rsc (pure . statusCode) + pure $ status /= 404 where req = method GET @@ -124,7 +124,7 @@ getConnection u = do rs <- sessionRequest req rsc consumeBody case statusCode rs of 200 -> responseJsonThrow (ParseError . pack) rs - 404 -> return Nothing + 404 -> pure Nothing _ -> unexpected rs "getConnection: status code" where req = diff --git a/libs/api-client/src/Network/Wire/Client/HTTP.hs b/libs/api-client/src/Network/Wire/Client/HTTP.hs index 4e5090d0fa1..20a4b499bd7 100644 --- a/libs/api-client/src/Network/Wire/Client/HTTP.hs +++ b/libs/api-client/src/Network/Wire/Client/HTTP.hs @@ -80,7 +80,7 @@ clientRequest rq expected f = do [ const $ Handler ( \(e :: ClientException) -> case e of - ErrorResponse c _ _ -> return (canRetry c) + ErrorResponse c _ _ -> pure (canRetry c) x -> throwIO x ), const $ Handler (\(e :: SomeException) -> throwIO e) @@ -123,6 +123,6 @@ mkErrorResponse rs = do (eitherDecode bdy) ) (responseBody r) - return $ case re of + pure $ case re of Left m -> ErrorResponse (statusCode rs) "N/A" m Right e -> ErrorResponse (code e) (label e) (message e) diff --git a/libs/api-client/src/Network/Wire/Client/Session.hs b/libs/api-client/src/Network/Wire/Client/Session.hs index 51aa5f0cad3..740a4c6ff9a 100644 --- a/libs/api-client/src/Network/Wire/Client/Session.hs +++ b/libs/api-client/src/Network/Wire/Client/Session.hs @@ -75,7 +75,7 @@ sessionRequest :: (Response BodyReader -> IO a) -> m a sessionRequest rq expected f = - either retry return + either retry pure =<< exec ( \rs -> if Bilge.statusCode rs == 401 diff --git a/libs/bilge/src/Bilge/Assert.hs b/libs/bilge/src/Bilge/Assert.hs index 03393bd9bc3..71159fcd04f 100644 --- a/libs/bilge/src/Bilge/Assert.hs +++ b/libs/bilge/src/Bilge/Assert.hs @@ -90,7 +90,7 @@ io String msg (i, Just m) = printf "%2d: " i ++ err m diff --git a/libs/bilge/src/Bilge/IO.hs b/libs/bilge/src/Bilge/IO.hs index 16db8d84c9d..18ed2b5b65c 100644 --- a/libs/bilge/src/Bilge/IO.hs +++ b/libs/bilge/src/Bilge/IO.hs @@ -128,7 +128,7 @@ instance MonadIO m => MonadHttp (HttpT m) where trivialBodyReader :: ByteString -> IO BodyReader trivialBodyReader bodyBytes = do bodyVar <- newTVarIO bodyBytes - return $ mkBodyReader bodyVar + pure $ mkBodyReader bodyVar where mkBodyReader :: TVar ByteString -> BodyReader mkBodyReader bodyVar = do @@ -270,7 +270,7 @@ http :: (Request -> Request) -> (Response BodyReader -> IO a) -> m a -http r f h = handleRequestWithCont (f r) h +http r f = handleRequestWithCont (f r) httpDebug :: (MonadIO m, MonadHttp m) => @@ -289,7 +289,7 @@ httpDebug debug r f h = do consumeBody >=> \rsp -> do if debug > Head then putStrLn (showResponse rsp) - else putStrLn (showResponse $ rsp {responseBody = ("" :: String)}) + else putStrLn (showResponse $ rsp {responseBody = "" :: String}) putStrLn "--" h rsp @@ -300,4 +300,4 @@ consumeBody r = do if null chunks then Nothing else Just (LBS.fromChunks chunks) - return $ r {responseBody = bdy} + pure $ r {responseBody = bdy} diff --git a/libs/bilge/src/Bilge/RPC.hs b/libs/bilge/src/Bilge/RPC.hs index fbdf4bae7bd..34bd8d059b2 100644 --- a/libs/bilge/src/Bilge/RPC.hs +++ b/libs/bilge/src/Bilge/RPC.hs @@ -95,7 +95,7 @@ rpc' sys r f = do res <- try $ httpLbs rq id case res of Left x -> throwM $ RPCException sys rq x - Right x -> return x + Right x -> pure x rpcExceptionMsg :: RPCException -> Msg -> Msg rpcExceptionMsg (RPCException sys req ex) = @@ -120,6 +120,6 @@ parseResponse :: (LText -> e) -> Response (Maybe LByteString) -> m a -parseResponse f r = either throwM return $ do +parseResponse f r = either throwM pure $ do b <- note (f "no response body") (responseBody r) fmapL (f . pack) (eitherDecode' b) diff --git a/libs/bilge/src/Bilge/Request.hs b/libs/bilge/src/Bilge/Request.hs index f7461d0523c..99d4acfc381 100644 --- a/libs/bilge/src/Bilge/Request.hs +++ b/libs/bilge/src/Bilge/Request.hs @@ -153,17 +153,15 @@ expectStatus :: (Int -> Bool) -> Request -> Request expectStatus property r = r {Rq.checkResponse = check} where check _ res - | property (HTTP.statusCode (Rq.responseStatus res)) = return () + | property (HTTP.statusCode (Rq.responseStatus res)) = pure () | otherwise = do some <- Lazy.toStrict <$> brReadSome (Rq.responseBody res) 1024 - throwHttp $ Rq.StatusCodeException (const () <$> res) some + throwHttp $ Rq.StatusCodeException (() <$ res) some checkStatus :: (Status -> ResponseHeaders -> CookieJar -> Maybe SomeException) -> Request -> Request checkStatus f r = r {Rq.checkResponse = check} where - check _ res = case mayThrow res of - Nothing -> return () - Just ex -> throwIO ex + check _ res = forM_ (mayThrow res) throwIO mayThrow res = f (Rq.responseStatus res) @@ -244,4 +242,4 @@ extPort :: URI.URI -> Maybe Word16 extPort u = do a <- u ^. URI.authorityL p <- a ^. URI.authorityPortL - return (fromIntegral (p ^. URI.portNumberL)) + pure (fromIntegral (p ^. URI.portNumberL)) diff --git a/libs/bilge/src/Bilge/Response.hs b/libs/bilge/src/Bilge/Response.hs index 22c1b755078..f8019c32f33 100644 --- a/libs/bilge/src/Bilge/Response.hs +++ b/libs/bilge/src/Bilge/Response.hs @@ -140,7 +140,7 @@ responseJsonUnsafeWithMsg :: responseJsonUnsafeWithMsg userErr = either err id . responseJsonEither where err parserErr = - error . intercalate " " $ + error . unwords $ ["responseJsonUnsafeWithMsg:"] <> [userErr | not $ null userErr] <> [parserErr] diff --git a/libs/bilge/src/Bilge/Retry.hs b/libs/bilge/src/Bilge/Retry.hs index 0b499b9c18d..01f2dc7ab01 100644 --- a/libs/bilge/src/Bilge/Retry.hs +++ b/libs/bilge/src/Bilge/Retry.hs @@ -26,12 +26,12 @@ import Network.HTTP.Client (HttpException (..), HttpExceptionContent (..), respo import Network.HTTP.Types httpHandlers :: Monad m => [a -> Handler m Bool] -httpHandlers = [const . Handler $ return . canRetry] +httpHandlers = [const . Handler $ pure . canRetry] rpcHandlers :: Monad m => [a -> Handler m Bool] rpcHandlers = [ const . Handler $ \(RPCException _ _ cause) -> - return $ maybe False canRetry (fromException cause) + pure $ maybe False canRetry (fromException cause) ] canRetry :: HttpException -> Bool diff --git a/libs/brig-types/src/Brig/Types/Common.hs b/libs/brig-types/src/Brig/Types/Common.hs index b92ec418674..a7a8b3a17a4 100644 --- a/libs/brig-types/src/Brig/Types/Common.hs +++ b/libs/brig-types/src/Brig/Types/Common.hs @@ -118,14 +118,14 @@ allPrefixes t = catMaybes $ parsePhonePrefix <$> Text.inits t instance FromJSON PhonePrefix where parseJSON = withText "PhonePrefix" $ \s -> case parsePhonePrefix s of - Just p -> return p + Just p -> pure p Nothing -> fail $ "Invalid phone number prefix: [" ++ show s ++ "]. Expected format similar to E.164 (with 1-15 digits after the +)." instance FromByteString PhonePrefix where - parser = parser >>= maybe (fail "Invalid phone") return . parsePhonePrefix + parser = parser >>= maybe (fail "Invalid phone") pure . parsePhonePrefix instance ToByteString PhonePrefix where builder = builder . fromPhonePrefix diff --git a/libs/brig-types/src/Brig/Types/Connection.hs b/libs/brig-types/src/Brig/Types/Connection.hs index f9f24145fa0..eaac6f88edf 100644 --- a/libs/brig-types/src/Brig/Types/Connection.hs +++ b/libs/brig-types/src/Brig/Types/Connection.hs @@ -1,6 +1,4 @@ -{-# LANGUAGE NamedFieldPuns #-} {-# LANGUAGE OverloadedStrings #-} -{-# LANGUAGE RecordWildCards #-} -- This file is part of the Wire Server implementation. -- diff --git a/libs/brig-types/src/Brig/Types/Instances.hs b/libs/brig-types/src/Brig/Types/Instances.hs index c9e19c77970..de70e73e798 100644 --- a/libs/brig-types/src/Brig/Types/Instances.hs +++ b/libs/brig-types/src/Brig/Types/Instances.hs @@ -32,14 +32,14 @@ import Imports instance Cql PrekeyId where ctype = Tagged IntColumn toCql = CqlInt . fromIntegral . keyId - fromCql (CqlInt i) = return $ PrekeyId (fromIntegral i) + fromCql (CqlInt i) = pure $ PrekeyId (fromIntegral i) fromCql _ = Left "PrekeyId: Int expected" instance Cql ServiceTag where ctype = Tagged BigIntColumn fromCql (CqlBigInt i) = case intToTag i of - Just t -> return t + Just t -> pure t Nothing -> Left $ "unexpected service tag: " ++ show i fromCql _ = Left "service tag: int expected" @@ -73,7 +73,7 @@ instance Cql ServiceKey where s <- required "size" p <- required "pem" case (t :: Int32) of - 0 -> return $! ServiceKey RsaServiceKey s p + 0 -> pure $! ServiceKey RsaServiceKey s p _ -> Left $ "Unexpected service key type: " ++ show t where required :: Cql r => Text -> Either String r diff --git a/libs/brig-types/src/Brig/Types/Intra.hs b/libs/brig-types/src/Brig/Types/Intra.hs index 65e7e822f91..a16610f0b0b 100644 --- a/libs/brig-types/src/Brig/Types/Intra.hs +++ b/libs/brig-types/src/Brig/Types/Intra.hs @@ -107,7 +107,7 @@ instance FromJSON UserAccount where parseJSON j@(Object o) = do u <- parseJSON j s <- o .: "status" - return $ UserAccount u s + pure $ UserAccount u s parseJSON _ = mzero instance ToJSON UserAccount where diff --git a/libs/brig-types/src/Brig/Types/Team/LegalHold.hs b/libs/brig-types/src/Brig/Types/Team/LegalHold.hs index 321f65f22ee..5156e6ca63b 100644 --- a/libs/brig-types/src/Brig/Types/Team/LegalHold.hs +++ b/libs/brig-types/src/Brig/Types/Team/LegalHold.hs @@ -1,4 +1,3 @@ -{-# LANGUAGE GeneralizedNewtypeDeriving #-} {-# LANGUAGE OverloadedStrings #-} -- This file is part of the Wire Server implementation. @@ -80,7 +79,7 @@ instance FromJSON LegalHoldService where <*> o .: "public_key" legalHoldService :: TeamId -> Fingerprint Rsa -> NewLegalHoldService -> ServiceKey -> LegalHoldService -legalHoldService tid fpr (NewLegalHoldService u _ t) k = LegalHoldService tid u fpr t k +legalHoldService tid fpr (NewLegalHoldService u _ t) = LegalHoldService tid u fpr t viewLegalHoldService :: LegalHoldService -> ViewLegalHoldService viewLegalHoldService (LegalHoldService tid u fpr t k) = diff --git a/libs/brig-types/test/unit/Test/Brig/Types/User.hs b/libs/brig-types/test/unit/Test/Brig/Types/User.hs index 5605784c55a..a3c2002bc9c 100644 --- a/libs/brig-types/test/unit/Test/Brig/Types/User.hs +++ b/libs/brig-types/test/unit/Test/Brig/Types/User.hs @@ -1,11 +1,9 @@ {-# LANGUAGE DataKinds #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE OverloadedStrings #-} -{-# LANGUAGE QuasiQuotes #-} {-# LANGUAGE ScopedTypeVariables #-} {-# LANGUAGE TypeApplications #-} {-# LANGUAGE TypeFamilies #-} -{-# LANGUAGE ViewPatterns #-} {-# OPTIONS_GHC -Wno-orphans #-} -- This file is part of the Wire Server implementation. diff --git a/libs/cassandra-util/src/Cassandra/Exec.hs b/libs/cassandra-util/src/Cassandra/Exec.hs index 6cb9c56129d..ae7589deb37 100644 --- a/libs/cassandra-util/src/Cassandra/Exec.hs +++ b/libs/cassandra-util/src/Cassandra/Exec.hs @@ -84,9 +84,9 @@ syncCassandra :: (Functor m, MonadIO m, MonadCatch m) => m a -> m (Either Cassan syncCassandra m = catches (Right <$> m) - [ Handler $ \(e :: Error) -> return . Left . Cassandra $ e, - Handler $ \(e :: IOException) -> return . Left . Comm $ e, - Handler $ \(e :: SomeException) -> return . Left . Other $ e + [ Handler $ \(e :: Error) -> pure . Left . Cassandra $ e, + Handler $ \(e :: IOException) -> pure . Left . Comm $ e, + Handler $ \(e :: SomeException) -> pure . Left . Other $ e ] -- | Stream results of a query. @@ -122,7 +122,7 @@ paginateWithState q p = do r <- runQ q p' getResult r >>= \case Protocol.RowsResult m b -> - return $ PageWithState b (pagingState m) + pure $ PageWithState b (pagingState m) _ -> throwM $ UnexpectedResponse (hrHost r) (hrResponse r) paramsPagingState :: Consistency -> a -> Int32 -> Maybe Protocol.PagingState -> QueryParams a diff --git a/libs/cassandra-util/src/Cassandra/Schema.hs b/libs/cassandra-util/src/Cassandra/Schema.hs index 4877f8df064..5205078b9ef 100644 --- a/libs/cassandra-util/src/Cassandra/Schema.hs +++ b/libs/cassandra-util/src/Cassandra/Schema.hs @@ -130,7 +130,7 @@ versionCheck v = do "Schema Version too old! Expecting at least: " <> show v <> ", but got: " - <> fromMaybe "" (show <$> v') + <> maybe "" show v' createKeyspace :: Keyspace -> ReplicationStrategy -> Client () createKeyspace (Keyspace k) rs = void $ schema (cql rs) (params All ()) @@ -231,7 +231,7 @@ waitForSchemaConsistency = do mbLocalVersion <- systemLocalVersion peers <- systemPeerVersions case mbLocalVersion of - Just localVersion -> return $ (localVersion, peers) + Just localVersion -> pure $ (localVersion, peers) Nothing -> error "No system_version in system.local (should never happen)" inDisagreement :: (UUID, [UUID]) -> Bool inDisagreement (localVersion, peers) = not $ all (== localVersion) peers @@ -252,43 +252,44 @@ retryWhileN :: (MonadIO m) => Int -> (a -> Bool) -> m a -> m a retryWhileN n f m = retrying (constantDelay 1000000 <> limitRetries n) - (const (return . f)) + (const (pure . f)) (const m) -- | The migrationPolicy selects only one and always the same host migrationPolicy :: IO Policy migrationPolicy = do h <- newIORef Nothing - return $ + pure $ Policy { setup = setHost h, - onEvent = const $ return (), + onEvent = const $ pure (), select = readIORef h, - acceptable = const $ return True, + acceptable = const $ pure True, hostCount = fromIntegral . length . maybeToList <$> readIORef h, display = ("migrationPolicy: " ++) . show <$> readIORef h, current = maybeToList <$> readIORef h } where setHost h (a : _) _ = writeIORef h (Just a) - setHost _ _ _ = return () + setHost _ _ _ = pure () migrationOptsParser :: Parser MigrationOpts migrationOptsParser = MigrationOpts - <$> ( strOption $ - long "host" - <> metavar "HOST" - <> value "localhost" - <> help "Cassandra host" - ) - <*> ( option auto $ - long "port" - <> metavar "PORT" - <> value 9042 - <> help "Cassandra port" - ) - <*> ( (fmap pack) . strOption $ + <$> strOption + ( long "host" + <> metavar "HOST" + <> value "localhost" + <> help "Cassandra host" + ) + <*> option + auto + ( long "port" + <> metavar "PORT" + <> value 9042 + <> help "Cassandra port" + ) + <*> ( fmap pack . strOption $ long "keyspace" <> metavar "STRING" <> help "Cassandra Keyspace" @@ -304,7 +305,7 @@ migrationOptsParser = <> help "Replication Map (i.e. \"eu-west:3,us-east:3\")" ) ) - <*> ( switch $ - long "reset" - <> help "Reset the keyspace before running migrations" - ) + <*> switch + ( long "reset" + <> help "Reset the keyspace before running migrations" + ) diff --git a/libs/cassandra-util/src/Cassandra/Settings.hs b/libs/cassandra-util/src/Cassandra/Settings.hs index c20a6dfc3ef..1fb3bf2007c 100644 --- a/libs/cassandra-util/src/Cassandra/Settings.hs +++ b/libs/cassandra-util/src/Cassandra/Settings.hs @@ -59,7 +59,7 @@ initialContactsDisco (pack -> srv) url = liftIO $ do . _String & map unpack case ip of - i : ii -> return (i :| ii) + i : ii -> pure (i :| ii) _ -> error "initial-contacts: no IP addresses found." -- | Puts the address into a list using the same signature as the other initialContacts diff --git a/libs/dns-util/src/Wire/Network/DNS/SRV.hs b/libs/dns-util/src/Wire/Network/DNS/SRV.hs index ee05c3b8373..597eaa9afcb 100644 --- a/libs/dns-util/src/Wire/Network/DNS/SRV.hs +++ b/libs/dns-util/src/Wire/Network/DNS/SRV.hs @@ -117,7 +117,7 @@ orderSrvResult = >>> fmap concat where orderSublist :: [SrvEntry] -> IO [SrvEntry] - orderSublist [] = return [] + orderSublist [] = pure [] orderSublist sublist = do -- Compute the running sum, as well as the total sum of the sublist. -- Add the running sum to the SRV tuples. @@ -129,10 +129,10 @@ orderSrvResult = -- than or equal to the random number. let (beginning, (firstSrv, _), end) = case break (\(_, running) -> randomNumber <= running) sublistWithRunning of - (b, (c : e)) -> (b, c, e) + (b, c : e) -> (b, c, e) _ -> error "orderSrvResult: no record with running sum greater than random number" -- Remove the running total number from the remaining elements. - let remainingSrvs = map fst (concat [beginning, end]) + let remainingSrvs = map fst (beginning ++ end) -- Repeat the ordering procedure on the remaining elements. rest <- orderSublist remainingSrvs - return $ firstSrv : rest + pure $ firstSrv : rest diff --git a/libs/extended/src/Servant/API/Extended.hs b/libs/extended/src/Servant/API/Extended.hs index 7f71777dd77..e0457115995 100644 --- a/libs/extended/src/Servant/API/Extended.hs +++ b/libs/extended/src/Servant/API/Extended.hs @@ -1,5 +1,3 @@ -{-# LANGUAGE GeneralizedNewtypeDeriving #-} - -- This file is part of the Wire Server implementation. -- -- Copyright (C) 2022 Wire Swiss GmbH diff --git a/libs/extended/src/System/Logger/Extended.hs b/libs/extended/src/System/Logger/Extended.hs index 9bf0cdddcf5..34de83ee421 100644 --- a/libs/extended/src/System/Logger/Extended.hs +++ b/libs/extended/src/System/Logger/Extended.hs @@ -149,9 +149,10 @@ netStringsToLogFormat False = Plain mkLogger :: Log.Level -> Maybe (Last Bool) -> Maybe (Last LogFormat) -> IO Log.Logger mkLogger lvl useNetstrings logFormat = do mkLoggerNew lvl $ - case (fmap netStringsToLogFormat <$> useNetstrings) <> logFormat of - Just x -> getLast x - Nothing -> Plain + maybe + Plain + getLast + ((fmap netStringsToLogFormat <$> useNetstrings) <> logFormat) -- | Version of mkLogger that doesn't support the deprecated useNetstrings option mkLoggerNew :: Log.Level -> LogFormat -> IO Log.Logger diff --git a/libs/galley-types/src/Galley/Types/Conversations/Roles.hs b/libs/galley-types/src/Galley/Types/Conversations/Roles.hs index c33dc0add21..48788a81168 100644 --- a/libs/galley-types/src/Galley/Types/Conversations/Roles.hs +++ b/libs/galley-types/src/Galley/Types/Conversations/Roles.hs @@ -53,7 +53,7 @@ isActionAllowed action rn -- | Custom RoleNames _must not_ start with `wire_` isCustomRoleName :: RoleName -> Bool -isCustomRoleName (fromRoleName -> r) = isValidRoleName r && (not $ "wire_" `T.isPrefixOf` r) +isCustomRoleName (fromRoleName -> r) = isValidRoleName r && not ("wire_" `T.isPrefixOf` r) roleNameToActions :: RoleName -> Maybe (Set Action) roleNameToActions r = roleActions <$> toConvRole r Nothing diff --git a/libs/galley-types/test/unit/Test/Galley/Types.hs b/libs/galley-types/test/unit/Test/Galley/Types.hs index 7f59c06e49f..996022d8b2a 100644 --- a/libs/galley-types/test/unit/Test/Galley/Types.hs +++ b/libs/galley-types/test/unit/Test/Galley/Types.hs @@ -1,4 +1,3 @@ -{-# LANGUAGE GeneralizedNewtypeDeriving #-} {-# LANGUAGE OverloadedStrings #-} {-# OPTIONS_GHC -Wno-orphans -Wno-incomplete-uni-patterns #-} diff --git a/libs/gundeck-types/src/Gundeck/Types/Common.hs b/libs/gundeck-types/src/Gundeck/Types/Common.hs index fad0df493de..37208a13398 100644 --- a/libs/gundeck-types/src/Gundeck/Types/Common.hs +++ b/libs/gundeck-types/src/Gundeck/Types/Common.hs @@ -58,4 +58,4 @@ instance FromByteString URI where parser = takeByteString >>= parse . Bytes.unpack parse :: (Monad m, MonadFail m) => String -> m URI -parse = maybe (fail "Invalid URI") (return . URI) . Net.parseURI +parse = maybe (fail "Invalid URI") (pure . URI) . Net.parseURI diff --git a/libs/gundeck-types/src/Gundeck/Types/Presence.hs b/libs/gundeck-types/src/Gundeck/Types/Presence.hs index 01895b6ccd3..40d9aa37da8 100644 --- a/libs/gundeck-types/src/Gundeck/Types/Presence.hs +++ b/libs/gundeck-types/src/Gundeck/Types/Presence.hs @@ -1,4 +1,3 @@ -{-# LANGUAGE GeneralizedNewtypeDeriving #-} {-# LANGUAGE OverloadedStrings #-} -- This file is part of the Wire Server implementation. diff --git a/libs/gundeck-types/src/Gundeck/Types/Push/V2.hs b/libs/gundeck-types/src/Gundeck/Types/Push/V2.hs index f1b708faddb..c491d89963f 100644 --- a/libs/gundeck-types/src/Gundeck/Types/Push/V2.hs +++ b/libs/gundeck-types/src/Gundeck/Types/Push/V2.hs @@ -101,9 +101,9 @@ data Route deriving (Eq, Ord, Enum, Bounded, Show) instance FromJSON Route where - parseJSON (String "any") = return RouteAny - parseJSON (String "direct") = return RouteDirect - parseJSON (String "native") = return RouteNative + parseJSON (String "any") = pure RouteAny + parseJSON (String "direct") = pure RouteDirect + parseJSON (String "native") = pure RouteNative parseJSON x = fail $ "Invalid routing: " ++ show (encode x) instance ToJSON Route where diff --git a/libs/metrics-core/src/Data/Metrics.hs b/libs/metrics-core/src/Data/Metrics.hs index 85ef0048451..b5fdcbd14c2 100644 --- a/libs/metrics-core/src/Data/Metrics.hs +++ b/libs/metrics-core/src/Data/Metrics.hs @@ -150,7 +150,7 @@ toInfo (Path p) = getOrCreate :: (MonadIO m, Eq k, Hashable k) => IORef (HashMap k v) -> k -> IO v -> m v getOrCreate mapRef key initializer = liftIO $ do hMap <- readIORef mapRef - maybe initialize return (HM.lookup key hMap) + maybe initialize pure (HM.lookup key hMap) where initialize = do val <- initializer diff --git a/libs/metrics-wai/src/Data/Metrics/Test.hs b/libs/metrics-wai/src/Data/Metrics/Test.hs index e7e34363ee5..50e07b98119 100644 --- a/libs/metrics-wai/src/Data/Metrics/Test.hs +++ b/libs/metrics-wai/src/Data/Metrics/Test.hs @@ -44,7 +44,7 @@ pathsConsistencyCheck :: Paths -> [SiteConsistencyError] pathsConsistencyCheck (Paths forest) = mconcat $ go [] <$> forest where go :: [PathSegment] -> Tree.Tree PathSegment -> [SiteConsistencyError] - go prefix (Tree.Node root trees) = maybeToList here <> (mconcat $ go (root : prefix) <$> trees) + go prefix (Tree.Node root trees) = maybeToList here <> mconcat (go (root : prefix) <$> trees) where here = findSiteConsistencyError (reverse $ root : prefix) trees findSiteConsistencyError :: [PathSegment] -> Tree.Forest PathSegment -> Maybe SiteConsistencyError diff --git a/libs/metrics-wai/src/Data/Metrics/WaiRoute.hs b/libs/metrics-wai/src/Data/Metrics/WaiRoute.hs index 92b953d377b..cd8a993c2cb 100644 --- a/libs/metrics-wai/src/Data/Metrics/WaiRoute.hs +++ b/libs/metrics-wai/src/Data/Metrics/WaiRoute.hs @@ -1,6 +1,4 @@ -{-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE ScopedTypeVariables #-} -{-# LANGUAGE ViewPatterns #-} -- This file is part of the Wire Server implementation. -- diff --git a/libs/ropes/src/Ropes/Nexmo.hs b/libs/ropes/src/Ropes/Nexmo.hs index 1de3ec41ad7..ba770c4db4d 100644 --- a/libs/ropes/src/Ropes/Nexmo.hs +++ b/libs/ropes/src/Ropes/Nexmo.hs @@ -2,7 +2,6 @@ {-# LANGUAGE GeneralizedNewtypeDeriving #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE ScopedTypeVariables #-} -{-# LANGUAGE ViewPatterns #-} -- This file is part of the Wire Server implementation. -- @@ -113,18 +112,18 @@ data MessageErrorStatus deriving (Eq, Show) instance FromJSON MessageErrorStatus where - parseJSON "1" = return MessageThrottled - parseJSON "5" = return MessageInternal - parseJSON "6" = return MessageUnroutable - parseJSON "7" = return MessageNumBarred - parseJSON "8" = return MessagePartnerAccountBarred - parseJSON "9" = return MessagePartnerQuotaExceeded - parseJSON "12" = return MessageTooLong - parseJSON "13" = return MessageCommunicationFailed - parseJSON "15" = return MessageInvalidSenderAddress - parseJSON "19" = return MessageFacilityNotAllowed - parseJSON "20" = return MessageInvalidMessageClass - parseJSON _ = return MessageOther + parseJSON "1" = pure MessageThrottled + parseJSON "5" = pure MessageInternal + parseJSON "6" = pure MessageUnroutable + parseJSON "7" = pure MessageNumBarred + parseJSON "8" = pure MessagePartnerAccountBarred + parseJSON "9" = pure MessagePartnerQuotaExceeded + parseJSON "12" = pure MessageTooLong + parseJSON "13" = pure MessageCommunicationFailed + parseJSON "15" = pure MessageInvalidSenderAddress + parseJSON "19" = pure MessageFacilityNotAllowed + parseJSON "20" = pure MessageInvalidMessageClass + parseJSON _ = pure MessageOther data MessageErrorResponse = MessageErrorResponse { erStatus :: !MessageErrorStatus, @@ -145,16 +144,16 @@ newtype ParseError = ParseError String instance Exception ParseError instance FromJSON MessageId where - parseJSON = withText "MessageId" $ return . MessageId + parseJSON = withText "MessageId" $ pure . MessageId instance ToJSON MessageId where toJSON = String . messageIdText instance FromJSON Charset where - parseJSON "text" = return GSM7 - parseJSON "binary" = return GSM8 - parseJSON "unicode" = return UCS2 - parseJSON x = fail $ "Unsupported charset " <> (show x) + parseJSON "text" = pure GSM7 + parseJSON "binary" = pure GSM8 + parseJSON "unicode" = pure UCS2 + parseJSON x = fail $ "Unsupported charset " <> show x instance ToJSON Charset where toJSON GSM7 = "text" @@ -179,8 +178,8 @@ parseMessageResponse = withObject "nexmo-response" $ \o -> do xs <- o .: "messages" ys <- sequence <$> mapM parseMessageFeedback xs case ys of - Left e -> return $ Left e - Right (f : fs) -> return $ Right $ MessageResponse (f :| fs) + Left e -> pure $ Left e + Right (f : fs) -> pure $ Right $ MessageResponse (f :| fs) Right _ -> fail "Must have at least one message-id" -- * Call related @@ -207,14 +206,14 @@ data CallErrorStatus deriving (Eq, Show) instance FromJSON CallErrorStatus where - parseJSON "1" = return CallThrottled - parseJSON "5" = return CallInternal - parseJSON "6" = return CallDestinationNotPermitted - parseJSON "7" = return CallDestinationBarred - parseJSON "9" = return CallPartnerQuotaExceeded - parseJSON "15" = return CallInvalidDestinationAddress - parseJSON "17" = return CallUnroutable - parseJSON _ = return CallOther + parseJSON "1" = pure CallThrottled + parseJSON "5" = pure CallInternal + parseJSON "6" = pure CallDestinationNotPermitted + parseJSON "7" = pure CallDestinationBarred + parseJSON "9" = pure CallPartnerQuotaExceeded + parseJSON "15" = pure CallInvalidDestinationAddress + parseJSON "17" = pure CallUnroutable + parseJSON _ = pure CallOther data CallErrorResponse = CallErrorResponse { caStatus :: !CallErrorStatus, @@ -264,7 +263,7 @@ sendCall cr mgr call = httpLbs req mgr >>= parseResult where parseResult res = case parseEither parseCallResponse =<< eitherDecode (responseBody res) of Left e -> throwIO $ ParseError e - Right r -> either throwIO return r + Right r -> either throwIO pure r req = defaultRequest { method = "POST", @@ -331,7 +330,7 @@ sendMessages cr mgr msgs = forM msgs $ \m -> httpLbs (req m) mgr >>= parseResult where parseResult res = case parseEither parseMessageResponse =<< eitherDecode (responseBody res) of Left e -> throwIO $ ParseError e - Right r -> either throwIO return r + Right r -> either throwIO pure r req m = defaultRequest { method = "POST", diff --git a/libs/ropes/src/Ropes/Twilio.hs b/libs/ropes/src/Ropes/Twilio.hs index eefbf53226a..5696708135e 100644 --- a/libs/ropes/src/Ropes/Twilio.hs +++ b/libs/ropes/src/Ropes/Twilio.hs @@ -142,9 +142,9 @@ instance FromJSON CarrierInfo where instance FromJSON PhoneType where parseJSON = withText "PhoneType" $ \t -> case t of - "mobile" -> return Mobile - "landline" -> return Landline - "voip" -> return VoIp + "mobile" -> pure Mobile + "landline" -> pure Landline + "voip" -> pure VoIp x -> fail $ "Unexpected phone type: " ++ show x -- * Functions @@ -161,7 +161,7 @@ sendMessages cr mgr msgs = forM msgs $ \m -> do rsp <- httpLbs req mgr if responseStatus rsp == status201 then case eitherDecode (responseBody rsp) of - Right r -> return $ msgId r + Right r -> pure $ msgId r Left e -> throwIO $ ParseError e else case eitherDecode (responseBody rsp) of Right e -> throwIO (e :: ErrorResponse) @@ -194,7 +194,7 @@ lookupPhone cr mgr phone detail country = do rsp <- httpLbs req mgr if responseStatus rsp == status200 then case eitherDecode (responseBody rsp) of - Right r -> return r + Right r -> pure r Left e -> throwIO $ ParseError e else case eitherDecode (responseBody rsp) of Right e -> throwIO (e :: ErrorResponse) diff --git a/libs/schema-profunctor/test/unit/Test/Data/Schema.hs b/libs/schema-profunctor/test/unit/Test/Data/Schema.hs index fac73016ea3..0a4c79d1929 100644 --- a/libs/schema-profunctor/test/unit/Test/Data/Schema.hs +++ b/libs/schema-profunctor/test/unit/Test/Data/Schema.hs @@ -351,7 +351,7 @@ testNullable = A.parse (schemaIn sch) A.Null @?= Success Nothing, testCase "Nullable schemas should produce either a value or null" $ do schemaOut sch (Just 5) @?= Just (A.Number 5) - schemaOut sch Nothing @?= Just (A.Null), + schemaOut sch Nothing @?= Just A.Null, testCase "Nullable schemas should return an error when parsing invalid non-null values" $ do case A.parse (schemaIn sch) (A.String "foo") of Success _ -> assertFailure "fromJSON should fail" diff --git a/libs/ssl-util/src/Ssl/Util.hs b/libs/ssl-util/src/Ssl/Util.hs index 5fc17fc3da6..9f9d8ece4e4 100644 --- a/libs/ssl-util/src/Ssl/Util.hs +++ b/libs/ssl-util/src/Ssl/Util.hs @@ -128,7 +128,7 @@ verifyFingerprint :: SSL -> IO () verifyFingerprint hash fprs ssl = do - cert <- SSL.getPeerCertificate ssl >>= maybe (throwIO PinMissingCert) return + cert <- SSL.getPeerCertificate ssl >>= maybe (throwIO PinMissingCert) pure pkey <- X509.getPublicKey cert mfpr <- hash pkey case mfpr of @@ -161,13 +161,13 @@ rsaFingerprint d k = fmap (digestLBS d . toLazyByteString) $ do let s = rsaSize k n <- integerToMPI (rsaN k) e <- integerToMPI (rsaE k) - return $! intDec s <> byteString n <> byteString e + pure $! intDec s <> byteString n <> byteString e -- | 'verifyFingerprint' specialised to 'RSAPubKey's using 'rsaFingerprint'. verifyRsaFingerprint :: Digest -> [ByteString] -> SSL -> IO () verifyRsaFingerprint d = verifyFingerprint $ \pk -> case toPublicKey pk of - Nothing -> return Nothing + Nothing -> pure Nothing Just k -> Just <$> rsaFingerprint d (k :: RSAPubKey) -- [Note: Hostname verification] diff --git a/libs/tasty-cannon/src/Test/Tasty/Cannon.hs b/libs/tasty-cannon/src/Test/Tasty/Cannon.hs index 57c8cfd78e9..f7f556886f1 100644 --- a/libs/tasty-cannon/src/Test/Tasty/Cannon.hs +++ b/libs/tasty-cannon/src/Test/Tasty/Cannon.hs @@ -114,7 +114,7 @@ connectAsMaybeClient can uid client conn = liftIO $ do nchan <- newTChanIO latch <- newEmptyMVar wsapp <- run can uid client conn (clientApp nchan latch) - return $ WebSocket nchan latch wsapp + pure $ WebSocket nchan latch wsapp close :: MonadIO m => WebSocket -> m () close ws = liftIO $ do @@ -299,7 +299,7 @@ awaitMatch t ws match = go [] [] do liftIO (match n) refill buf - return (Right n) + pure (Right n) `catchAll` \e -> case asyncExceptionFromException e of Just x -> throwM (x :: SomeAsyncException) Nothing -> @@ -307,7 +307,7 @@ awaitMatch t ws match = go [] [] in go (n : buf) (e' : errs) Nothing -> do refill buf - return (Left (MatchTimeout errs)) + pure (Left (MatchTimeout errs)) refill = mapM_ (liftIO . atomically . writeTChan (wsChan ws)) awaitMatch_ :: @@ -367,7 +367,7 @@ assertMatchN_ :: assertMatchN_ t wss f = void $ assertMatchN t wss f assertSuccess :: (HasCallStack, MonadIO m, MonadThrow m) => Either MatchTimeout Notification -> m Notification -assertSuccess = either throwM return +assertSuccess = either throwM pure assertNoEvent :: (HasCallStack, MonadIO m, MonadCatch m) => Timeout -> [WebSocket] -> m () assertNoEvent t ww = do @@ -393,7 +393,7 @@ unpackPayload = fmap decodeEvent . ntfPayload randomConnId :: MonadIO m => m ConnId randomConnId = liftIO $ do r <- randomIO :: IO Word32 - return . ConnId $ C.pack $ show r + pure . ConnId $ C.pack $ show r ----------------------------------------------------------------------------- -- Internals @@ -419,7 +419,7 @@ run cannon@(($ Http.defaultRequest) -> ca) uid client connId app = liftIO $ do stat <- poll wsapp case stat of Just (Left ex) -> throwIO ex - _ -> waitForRegistry numRetries >> return wsapp + _ -> waitForRegistry numRetries >> pure wsapp where caHost = C.unpack (Http.host ca) caPort = Http.port ca diff --git a/libs/types-common-aws/src/Util/Test/SQS.hs b/libs/types-common-aws/src/Util/Test/SQS.hs index a0c86086bd5..e68e684484e 100644 --- a/libs/types-common-aws/src/Util/Test/SQS.hs +++ b/libs/types-common-aws/src/Util/Test/SQS.hs @@ -2,7 +2,6 @@ {-# LANGUAGE GADTs #-} {-# LANGUAGE MultiParamTypeClasses #-} {-# LANGUAGE OverloadedStrings #-} -{-# LANGUAGE StandaloneDeriving #-} {-# LANGUAGE TypeFamilies #-} {-# LANGUAGE UndecidableInstances #-} @@ -62,7 +61,7 @@ readAndDeleteAllUntilEmpty url = do firstBatch <- fromMaybe [] . view SQS.receiveMessageResponse_messages <$> sendEnv (receive 1 url) readUntilEmpty firstBatch firstBatch where - readUntilEmpty acc [] = return acc + readUntilEmpty acc [] = pure acc readUntilEmpty acc msgs = do forM_ msgs $ deleteMessage url newMsgs <- fromMaybe [] . view SQS.receiveMessageResponse_messages <$> sendEnv (receive 1 url) @@ -101,13 +100,14 @@ fetchMessage url label callback = do parseDeleteMessage :: (Monad m, Message a, MonadIO m, MonadReader AWS.Env m, MonadResource m) => Text -> SQS.Message -> m (Maybe a) parseDeleteMessage url m = do - evt <- case (>>= decodeMessage) . B64.decode . Text.encodeUtf8 <$> (m ^. SQS.message_body) of - Just (Right e) -> return (Just e) + let decodedMessage = decodeMessage <=< (B64.decode . Text.encodeUtf8) + evt <- case decodedMessage <$> (m ^. SQS.message_body) of + Just (Right e) -> pure (Just e) _ -> do liftIO $ print ("Failed to parse SQS message or event" :: String) - return Nothing + pure Nothing deleteMessage url m - return evt + pure evt queueMessage :: (MonadReader AWS.Env m, Message a, MonadResource m) => Text -> a -> m () queueMessage url e = do @@ -143,10 +143,10 @@ tryMatch label tries url callback = go tries check e = do liftIO $ callback label e - return (Right $ show e) + pure (Right $ show e) `catchAll` \ex -> case asyncExceptionFromException ex of Just x -> throwM (x :: SomeAsyncException) - Nothing -> return . Left $ MatchFailure (e, ex) + Nothing -> pure . Left $ MatchFailure (e, ex) sendEnv :: (MonadReader AWS.Env m, MonadResource m, AWS.AWSRequest a) => a -> m (AWS.AWSResponse a) sendEnv x = flip AWS.send x =<< ask diff --git a/libs/types-common/src/Data/Id.hs b/libs/types-common/src/Data/Id.hs index b587f102d15..bcdd57aa121 100644 --- a/libs/types-common/src/Data/Id.hs +++ b/libs/types-common/src/Data/Id.hs @@ -61,6 +61,7 @@ import qualified Data.Aeson.Key as Key import qualified Data.Aeson.Types as A import Data.Attoparsec.ByteString (()) import qualified Data.Attoparsec.ByteString.Char8 as Atto +import Data.Bifunctor (first) import Data.Binary import Data.ByteString.Builder (byteString) import Data.ByteString.Conversion @@ -173,7 +174,7 @@ instance Show (Id a) where show = UUID.toString . toUUID instance Read (Id a) where - readsPrec n = map (\(a, x) -> (Id a, x)) . readsPrec n + readsPrec n = map (first Id) . readsPrec n instance FromByteString (Id a) where parser = do @@ -189,7 +190,7 @@ instance FromByteString (Id a) where void $ Atto.count 12 hexDigit case UUID.fromASCIIBytes match of Nothing -> fail "Invalid UUID" - Just ui -> return (Id ui) + Just ui -> pure (Id ui) where matching = fmap fst . Atto.match hexDigit = Atto.satisfy Char.isHexDigit "hexadecimal digit" @@ -315,7 +316,7 @@ instance EncodeWire ClientId where encodeWire t = encodeWire t . client instance DecodeWire ClientId where - decodeWire (DelimitedField _ x) = either fail return (runParser parser x) + decodeWire (DelimitedField _ x) = either fail pure (runParser parser x) decodeWire _ = fail "Invalid ClientId" -- BotId ----------------------------------------------------------------------- @@ -339,7 +340,7 @@ instance Show BotId where show = show . botUserId instance Read BotId where - readsPrec n = map (\(a, x) -> (BotId a, x)) . readsPrec n + readsPrec n = map (first BotId) . readsPrec n deriving instance Cql BotId diff --git a/libs/types-common/src/Data/Misc.hs b/libs/types-common/src/Data/Misc.hs index 85ad78537c0..0807be0e76e 100644 --- a/libs/types-common/src/Data/Misc.hs +++ b/libs/types-common/src/Data/Misc.hs @@ -103,7 +103,7 @@ instance FromByteString IpAddr where s <- Chars.takeWhile1 (not . isSpace) case readMaybe (unpack s) of Nothing -> fail "Failed parsing bytestring as IpAddr." - Just ip -> return (IpAddr ip) + Just ip -> pure (IpAddr ip) instance ToByteString IpAddr where builder = string8 . show . ipAddr @@ -136,7 +136,7 @@ instance FromJSON IpAddr where parseJSON = A.withText "IpAddr" $ \txt -> case readMaybe (Text.unpack txt) of Nothing -> fail "Failed parsing IP address." - Just ip -> return (IpAddr ip) + Just ip -> pure (IpAddr ip) instance ToJSON Port where toJSON (Port p) = toJSON p @@ -198,7 +198,7 @@ instance Cql Latitude where toCql (Latitude x) = CqlDouble x - fromCql (CqlDouble x) = return (Latitude x) + fromCql (CqlDouble x) = pure (Latitude x) fromCql _ = Left "Latitude: Expected CqlDouble." instance Cql Longitude where @@ -206,7 +206,7 @@ instance Cql Longitude where toCql (Longitude x) = CqlDouble x - fromCql (CqlDouble x) = return (Longitude x) + fromCql (CqlDouble x) = pure (Longitude x) fromCql _ = Left "Longitude: Expected CqlDouble." -------------------------------------------------------------------------------- @@ -329,7 +329,7 @@ instance Cql (Fingerprint a) where ctype = Tagged BlobColumn toCql = CqlBlob . toByteString - fromCql (CqlBlob b) = return (Fingerprint (toStrict b)) + fromCql (CqlBlob b) = pure (Fingerprint (toStrict b)) fromCql _ = Left "Fingerprint: Expected CqlBlob" instance Arbitrary (Fingerprint Rsa) where diff --git a/libs/types-common/src/Data/Range.hs b/libs/types-common/src/Data/Range.hs index 5589004e35c..137b1ed8403 100644 --- a/libs/types-common/src/Data/Range.hs +++ b/libs/types-common/src/Data/Range.hs @@ -116,7 +116,7 @@ instance ToJSON a => ToJSON (Range n m a) where toJSON = toJSON . fromRange instance (Within a n m, FromJSON a) => FromJSON (Range n m a) where - parseJSON v = parseJSON v >>= maybe (msg sing sing) return . checked + parseJSON v = parseJSON v >>= maybe (msg sing sing) pure . checked where msg :: Bounds a => SNat n -> SNat m -> Aeson.Parser (Range n m a) msg sn sm = fail (errorMsg (fromSing sn) (fromSing sm) "") @@ -184,7 +184,7 @@ instance (Within a n m, ToSchema a, HasRangedSchemaDocModifier NamedSwaggerDoc a instance (Within a n m, Cql a) => Cql (Range n m a) where ctype = retag (ctype :: Tagged a ColumnType) toCql = toCql . fromRange - fromCql c = fromCql c >>= maybe (msg sing sing) return . checked + fromCql c = fromCql c >>= maybe (msg sing sing) pure . checked where msg :: Bounds a => SNat n -> SNat m -> Either String (Range n m a) msg sn sm = Left (errorMsg (fromSing sn) (fromSing sm) "") @@ -423,7 +423,7 @@ instance (Within a n m, Read a) => Read (Range n m a) where ----------------------------------------------------------------------------- instance (Within a n m, FromByteString a) => FromByteString (Range n m a) where - parser = parser >>= maybe (msg sing sing) return . checked + parser = parser >>= maybe (msg sing sing) pure . checked where msg :: Bounds a => SNat n -> SNat m -> Atto.Parser (Range n m a) msg sn sm = fail (errorMsg (fromSing sn) (fromSing sm) "") @@ -496,8 +496,7 @@ genRangeAsciiText :: (HasCallStack, KnownNat n, KnownNat m, LTE n m, AsciiChars c) => Gen (AsciiChar c) -> Gen (Range n m (AsciiText c)) -genRangeAsciiText gc = - genRange @n @m fromAsciiChars gc +genRangeAsciiText = genRange @n @m fromAsciiChars genRange :: forall (n :: Nat) (m :: Nat) (a :: *) (b :: *). diff --git a/libs/types-common/src/Data/Text/Ascii.hs b/libs/types-common/src/Data/Text/Ascii.hs index 0a993c3a1a8..bc669d5bd61 100644 --- a/libs/types-common/src/Data/Text/Ascii.hs +++ b/libs/types-common/src/Data/Text/Ascii.hs @@ -4,7 +4,6 @@ {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE GeneralizedNewtypeDeriving #-} {-# LANGUAGE TypeFamilies #-} -{-# LANGUAGE TypeSynonymInstances #-} -- This file is part of the Wire Server implementation. -- diff --git a/libs/types-common/src/Util/Options.hs b/libs/types-common/src/Util/Options.hs index 95d269110af..c3991f40180 100644 --- a/libs/types-common/src/Util/Options.hs +++ b/libs/types-common/src/Util/Options.hs @@ -47,31 +47,31 @@ instance FromByteString AWSEndpoint where parser = do url <- uriParser strictURIParserOptions secure <- case url ^. uriSchemeL . schemeBSL of - "https" -> return True - "http" -> return False + "https" -> pure True + "http" -> pure False x -> fail ("Unsupported scheme: " ++ show x) - host <- case (url ^. authorityL <&> view (authorityHostL . hostBSL)) of - Just h -> return h + host <- case url ^. authorityL <&> view (authorityHostL . hostBSL) of + Just h -> pure h Nothing -> fail ("No host in: " ++ show url) port <- case urlPort url of - Just p -> return p + Just p -> pure p Nothing -> - return $ + pure $ if secure then 443 else 80 - return $ AWSEndpoint host secure port + pure $ AWSEndpoint host secure port instance FromJSON AWSEndpoint where parseJSON = withText "AWSEndpoint" $ - either fail return . runParser parser . encodeUtf8 + either fail pure . runParser parser . encodeUtf8 urlPort :: URIRef Absolute -> Maybe Int urlPort u = do a <- u ^. authorityL p <- a ^. authorityPortL - return (fromIntegral (p ^. portNumberL)) + pure (fromIntegral (p ^. portNumberL)) makeLenses ''AWSEndpoint @@ -109,8 +109,8 @@ loadSecret (FilePathSecrets p) = do path <- canonicalizePath p exists <- doesFileExist path if exists - then return . over _Left show . decodeEither' =<< BS.readFile path - else return (Left "File doesn't exist") + then over _Left show . decodeEither' <$> BS.readFile path + else pure (Left "File doesn't exist") getOptions :: FromJSON a => @@ -130,7 +130,7 @@ getOptions desc pars defaultPath = do configFile <- decodeFileEither path case configFile of Left e -> fail $ show e - Right o -> return o + Right o -> pure o -- Config doesn't exist but at least we have a CLI options parser (False, Just p) -> do hPutStrLn stderr $ @@ -160,7 +160,7 @@ parseConfigPath defaultPath desc = do <> value defaultPath parseAWSEndpoint :: ReadM AWSEndpoint -parseAWSEndpoint = readerAsk >>= maybe (error "Could not parse AWS endpoint") return . fromByteString . fromString +parseAWSEndpoint = readerAsk >>= maybe (error "Could not parse AWS endpoint") pure . fromByteString . fromString discoUrlParser :: Parser Text discoUrlParser = diff --git a/libs/types-common/src/Util/Options/Common.hs b/libs/types-common/src/Util/Options/Common.hs index 13e52e51977..39adc0092f3 100644 --- a/libs/types-common/src/Util/Options/Common.hs +++ b/libs/types-common/src/Util/Options/Common.hs @@ -1,7 +1,3 @@ -{-# LANGUAGE DeriveGeneric #-} -{-# LANGUAGE GeneralizedNewtypeDeriving #-} -{-# LANGUAGE TemplateHaskell #-} - -- This file is part of the Wire Server implementation. -- -- Copyright (C) 2022 Wire Swiss GmbH @@ -50,7 +46,7 @@ toOptionFieldName = defaultOptions {fieldLabelModifier = lowerFirst . dropPrefix dropPrefix :: String -> String dropPrefix = dropWhile (not . isUpper) -optOrEnv :: (a -> b) -> (Maybe a) -> (String -> b) -> String -> IO b +optOrEnv :: (a -> b) -> Maybe a -> (String -> b) -> String -> IO b optOrEnv getter conf reader var = case conf of Nothing -> reader <$> getEnv var Just c -> pure $ getter c diff --git a/libs/types-common/src/Util/Test.hs b/libs/types-common/src/Util/Test.hs index e83d190dd81..33a185e713c 100644 --- a/libs/types-common/src/Util/Test.hs +++ b/libs/types-common/src/Util/Test.hs @@ -1,6 +1,4 @@ -{-# LANGUAGE DeriveGeneric #-} {-# LANGUAGE OverloadedStrings #-} -{-# LANGUAGE TemplateHaskell #-} -- This file is part of the Wire Server implementation. -- @@ -32,12 +30,12 @@ newtype IntegrationConfigFile = IntegrationConfigFile String instance IsOption IntegrationConfigFile where defaultValue = IntegrationConfigFile "/etc/wire/integration/integration.yaml" parseValue = fmap IntegrationConfigFile . safeRead - optionName = return "integration-config" - optionHelp = return "Integration config file to read from" + optionName = pure "integration-config" + optionHelp = pure "Integration config file to read from" optionCLParser = fmap IntegrationConfigFile $ strOption $ - ( short (untag (return 'i' :: Tagged IntegrationConfigFile Char)) + ( short (untag (pure 'i' :: Tagged IntegrationConfigFile Char)) <> long (untag (optionName :: Tagged IntegrationConfigFile String)) <> help (untag (optionHelp :: Tagged IntegrationConfigFile String)) ) diff --git a/libs/wai-utilities/src/Network/Wai/Utilities/Error.hs b/libs/wai-utilities/src/Network/Wai/Utilities/Error.hs index bd8f127c44e..9bd1f39d154 100644 --- a/libs/wai-utilities/src/Network/Wai/Utilities/Error.hs +++ b/libs/wai-utilities/src/Network/Wai/Utilities/Error.hs @@ -79,7 +79,7 @@ instance ToJSON Error where "label" .= l, "message" .= m ] - ++ fromMaybe [] (fmap dataFields md) + ++ maybe [] dataFields md where dataFields :: ErrorData -> [Pair] dataFields d = ["data" .= d] diff --git a/libs/wai-utilities/src/Network/Wai/Utilities/Request.hs b/libs/wai-utilities/src/Network/Wai/Utilities/Request.hs index c07d29782ae..878311f1640 100644 --- a/libs/wai-utilities/src/Network/Wai/Utilities/Request.hs +++ b/libs/wai-utilities/src/Network/Wai/Utilities/Request.hs @@ -82,7 +82,7 @@ jsonRequest :: Predicate r Error (JsonRequest body) jsonRequest = contentType "application" "json" - .&> (return . JsonRequest . getRequest) + .&> (pure . JsonRequest . getRequest) newtype OptionalJsonRequest body = OptionalJsonRequest {fromOptionalJsonRequest :: Request} @@ -92,7 +92,7 @@ optionalJsonRequest :: Predicate r Error (OptionalJsonRequest body) optionalJsonRequest = opt (contentType "application" "json") - .&> (return . OptionalJsonRequest . getRequest) + .&> (pure . OptionalJsonRequest . getRequest) ---------------------------------------------------------------------------- -- Instances diff --git a/libs/wai-utilities/src/Network/Wai/Utilities/Server.hs b/libs/wai-utilities/src/Network/Wai/Utilities/Server.hs index ed679c8780d..8bbf5286490 100644 --- a/libs/wai-utilities/src/Network/Wai/Utilities/Server.hs +++ b/libs/wai-utilities/src/Network/Wai/Utilities/Server.hs @@ -103,11 +103,11 @@ newSettings (Server h p l m t) = do -- (Atomically) initialise the standard metrics, to avoid races. void $ gaugeGet (path "net.connections") m void $ counterGet (path "net.errors") m - return $ + pure $ setHost (fromString h) . setPort (fromIntegral p) . setBeforeMainLoop logStart - . setOnOpen (const $ connStart >> return True) + . setOnOpen (const $ connStart >> pure True) . setOnClose (const connEnd) . setTimeout (fromMaybe 300 t) $ defaultSettings @@ -148,7 +148,7 @@ runSettingsWithShutdown s app secs = do compile :: Monad m => Routes a m b -> Tree (App m) compile routes = Route.prepare (Route.renderer predicateError >> routes) where - predicateError e = return (encode $ Wai.mkError (P.status e) "client-error" (format e), [jsonContent]) + predicateError e = pure (encode $ Wai.mkError (P.status e) "client-error" (format e), [jsonContent]) -- [label] 'source' reason: message format e = let l = labelStr $ labels e @@ -277,14 +277,14 @@ emitLByteString :: LByteString -> IO (IO ByteString) emitLByteString lbs = do tvar <- newTVarIO (cs lbs) -- Emit the bytestring on the first read, then always return "" on subsequent reads - return . atomically $ swapTVar tvar mempty + pure . atomically $ swapTVar tvar mempty -- | Run the 'Application'; check the response status; if >=500, throw a 'Wai.Error' with -- label @"server-error"@ and the body as the error message. rethrow5xx :: Logger -> Middleware rethrow5xx logger app req k = app req k' where - k' resp@(WaiInt.ResponseRaw {}) = do + k' resp@WaiInt.ResponseRaw {} = do -- See Note [Raw Response] let logMsg = field "canoncalpath" (show $ pathInfo req) @@ -362,7 +362,7 @@ logErrorMsg :: Wai.Error -> Msg -> Msg logErrorMsg (Wai.Error c l m md) = field "code" (statusCode c) . field "label" l - . fromMaybe id (fmap logErrorData md) + . maybe id logErrorData md . msg (val "\"" +++ m +++ val "\"") where logErrorData (Wai.FederationErrorData d p) = diff --git a/libs/wai-utilities/src/Network/Wai/Utilities/ZAuth.hs b/libs/wai-utilities/src/Network/Wai/Utilities/ZAuth.hs index 14f2fc7a92e..c70d65f7a67 100644 --- a/libs/wai-utilities/src/Network/Wai/Utilities/ZAuth.hs +++ b/libs/wai-utilities/src/Network/Wai/Utilities/ZAuth.hs @@ -73,7 +73,7 @@ zauthType = zheader "Z-Type" zauth :: HasHeaders r => ZAuthType -> Predicate r Error () zauth t = do r <- zauthType - return $ case r of + pure $ case r of Okay _ z | z == t -> Okay 0 () _ -> Fail accessDenied diff --git a/libs/wire-api-federation/src/Wire/API/Federation/Client.hs b/libs/wire-api-federation/src/Wire/API/Federation/Client.hs index 7b6a601156a..a2f3f1896fa 100644 --- a/libs/wire-api-federation/src/Wire/API/Federation/Client.hs +++ b/libs/wire-api-federation/src/Wire/API/Federation/Client.hs @@ -38,6 +38,7 @@ import Control.Monad.Codensity import Control.Monad.Except import Control.Monad.Trans.Maybe import qualified Data.Aeson as Aeson +import Data.Bifunctor (first) import qualified Data.ByteString as BS import Data.ByteString.Builder import Data.ByteString.Conversion (toByteString') @@ -112,8 +113,7 @@ liftCodensity :: Codensity IO a -> FederatorClient c a liftCodensity = FederatorClient . lift . lift . lift headersFromTable :: HTTP2.HeaderTable -> [HTTP.Header] -headersFromTable (headerList, _) = flip map headerList $ \(token, headerValue) -> - (HTTP2.tokenKey token, headerValue) +headersFromTable (headerList, _) = flip map headerList $ first HTTP2.tokenKey connectSocket :: ByteString -> Int -> IO NS.Socket connectSocket hostname port = @@ -130,7 +130,7 @@ performHTTP2Request :: performHTTP2Request mtlsConfig req hostname port = try $ do withHTTP2Request mtlsConfig req hostname port $ \resp -> do b <- - fmap (either (const mempty) id) + fmap (fromRight mempty) . runExceptT . runSourceT . responseBody @@ -199,12 +199,11 @@ instance KnownComponent c => RunStreamingClient (FederatorClient c) where withStreamingRequest = withHTTP2StreamingRequest HTTP.statusIsSuccessful streamingResponseStrictBody :: StreamingResponse -> IO Builder -streamingResponseStrictBody resp = +streamingResponseStrictBody = fmap (either stringUtf8 (foldMap byteString)) . runExceptT . runSourceT . responseBody - $ resp -- Perform a streaming request to the local federator. withHTTP2StreamingRequest :: @@ -225,13 +224,11 @@ withHTTP2StreamingRequest successfulStatus req handleResponse = do let path = baseUrlPath <> requestPath req body <- do - body <- case requestBody req of + case requestBody req of Just (RequestBodyLBS lbs, _) -> pure lbs Just (RequestBodyBS bs, _) -> pure (LBS.fromStrict bs) - Just (RequestBodySource _, _) -> - throwError FederatorClientStreamingNotSupported + Just (RequestBodySource _, _) -> throwError FederatorClientStreamingNotSupported Nothing -> pure mempty - pure body let req' = HTTP2.requestBuilder (requestMethod req) @@ -240,7 +237,7 @@ withHTTP2StreamingRequest successfulStatus req handleResponse = do (lazyByteString body) let Endpoint (Text.encodeUtf8 -> hostname) (fromIntegral -> port) = ceFederator env resp <- - (either throwError pure =<<) . liftCodensity $ + either throwError pure <=< liftCodensity $ Codensity $ \k -> E.catch (withHTTP2Request Nothing req' hostname port (k . Right)) @@ -326,9 +323,11 @@ runVersionedFederatorClientToCodensity :: ExceptT FederatorClientError (Codensity IO) a runVersionedFederatorClientToCodensity env = flip runReaderT env - . (maybe (E.throw FederatorClientVersionMismatch) pure =<<) + . unmaybe . runMaybeT . unFederatorClient + where + unmaybe = (maybe (E.throw FederatorClientVersionMismatch) pure =<<) versionNegotiation :: FederatorClient 'Brig Version versionNegotiation = diff --git a/libs/wire-api/src/Wire/API/Routes/Public/Brig.hs b/libs/wire-api/src/Wire/API/Routes/Public/Brig.hs index fc590359120..f424a110781 100644 --- a/libs/wire-api/src/Wire/API/Routes/Public/Brig.hs +++ b/libs/wire-api/src/Wire/API/Routes/Public/Brig.hs @@ -803,30 +803,28 @@ type MLSKeyPackageAPI = :> ReqBody '[JSON] KeyPackageUpload :> MultiVerb 'POST '[JSON, MLS] '[RespondEmpty 201 "Key packages uploaded"] () ) - :<|> ( Named - "mls-key-packages-claim" - ( "claim" - :> Summary "Claim one key package for each client of the given user" - :> QualifiedCaptureUserId "user" - :> QueryParam' - [ Optional, - Strict, - Description "Do not claim a key package for the given own client" - ] - "skip_own" - ClientId - :> MultiVerb1 'POST '[JSON] (Respond 200 "Claimed key packages" KeyPackageBundle) - ) - ) - :<|> ( Named - "mls-key-packages-count" - ( "self" - :> CaptureClientId "client" - :> "count" - :> Summary "Return the number of unused key packages for the given client" - :> MultiVerb1 'GET '[JSON] (Respond 200 "Number of key packages" KeyPackageCount) - ) - ) + :<|> Named + "mls-key-packages-claim" + ( "claim" + :> Summary "Claim one key package for each client of the given user" + :> QualifiedCaptureUserId "user" + :> QueryParam' + [ Optional, + Strict, + Description "Do not claim a key package for the given own client" + ] + "skip_own" + ClientId + :> MultiVerb1 'POST '[JSON] (Respond 200 "Claimed key packages" KeyPackageBundle) + ) + :<|> Named + "mls-key-packages-count" + ( "self" + :> CaptureClientId "client" + :> "count" + :> Summary "Return the number of unused key packages for the given client" + :> MultiVerb1 'GET '[JSON] (Respond 200 "Number of key packages" KeyPackageCount) + ) ) type MLSAPI = LiftNamed (ZLocalUser :> "mls" :> MLSKeyPackageAPI) diff --git a/libs/zauth/main/Main.hs b/libs/zauth/main/Main.hs index 61e00e41933..e09be731bfc 100644 --- a/libs/zauth/main/Main.hs +++ b/libs/zauth/main/Main.hs @@ -102,14 +102,14 @@ go CreateAccess o = do go CreateBot o = do when (length (o ^. dat) /= 3) $ error "invalid --data, must have 3 elements" - let p = uuid $ (o ^. dat) !! 0 + let p = uuid $ head (o ^. dat) b = uuid $ (o ^. dat) !! 1 c = uuid $ (o ^. dat) !! 2 runCreate' o $ toByteString <$> botToken p b c go CreateProvider o = do when (length (o ^. dat) /= 1) $ error "missing --data" - let p = uuid $ (o ^. dat) !! 0 + let p = uuid $ head (o ^. dat) runCreate' o $ toByteString <$> providerToken (o ^. dur) p go GenKeyPair _ = do (p, s) <- newKeyPair @@ -123,7 +123,7 @@ uuid :: ByteString -> UUID uuid s = fromMaybe (error $ "Invalid UUID: " ++ show s) $ fromASCIIBytes s check' :: ToByteString a => ByteString -> Token a -> IO () -check' k t = exceptT (\e -> putStrLn e >> exitFailure) (const $ return ()) $ do +check' k t = exceptT (\e -> putStrLn e >> exitFailure) (const $ pure ()) $ do p <- hoistEither $ PublicKey <$> decode k e <- liftIO $ runValidate (V.mkEnv p (replicate (t ^. header . key) p)) (check t) hoistEither $ fmapL show e @@ -181,14 +181,14 @@ options = <> help "token data" toMode = readerAsk >>= \s -> case s of - "create-user" -> return CreateUser - "create-session" -> return CreateSession - "create-access" -> return CreateAccess - "create-bot" -> return CreateBot - "create-provider" -> return CreateProvider - "verify-user" -> return VerifyUser - "verify-access" -> return VerifyAccess - "verify-bot" -> return VerifyBot - "verify-provider" -> return VerifyProvider - "gen-keypair" -> return GenKeyPair + "create-user" -> pure CreateUser + "create-session" -> pure CreateSession + "create-access" -> pure CreateAccess + "create-bot" -> pure CreateBot + "create-provider" -> pure CreateProvider + "verify-user" -> pure VerifyUser + "verify-access" -> pure VerifyAccess + "verify-bot" -> pure VerifyBot + "verify-provider" -> pure VerifyProvider + "gen-keypair" -> pure GenKeyPair other -> readerError $ "invalid mode: " <> other diff --git a/libs/zauth/src/Data/ZAuth/Creation.hs b/libs/zauth/src/Data/ZAuth/Creation.hs index 003dd4c2598..179317a7263 100644 --- a/libs/zauth/src/Data/ZAuth/Creation.hs +++ b/libs/zauth/src/Data/ZAuth/Creation.hs @@ -156,7 +156,7 @@ newToken ti ty ta a = do k <- Create $ asks keyIdx let h = mkHeader tokenVersion k (floor ti) ty ta s <- signToken h a - return $ mkToken s h a + pure $ mkToken s h a ----------------------------------------------------------------------------- -- Internal diff --git a/libs/zauth/src/Data/ZAuth/Token.hs b/libs/zauth/src/Data/ZAuth/Token.hs index 52ea198c456..a4319822dcd 100644 --- a/libs/zauth/src/Data/ZAuth/Token.hs +++ b/libs/zauth/src/Data/ZAuth/Token.hs @@ -189,42 +189,42 @@ instance FromByteString (Token Access) where takeLazyByteString >>= \b -> case readToken A readAccessBody b of Nothing -> fail "Invalid access token" - Just t -> return t + Just t -> pure t instance FromByteString (Token User) where parser = takeLazyByteString >>= \b -> case readToken U readUserBody b of Nothing -> fail "Invalid user token" - Just t -> return t + Just t -> pure t instance FromByteString (Token Bot) where parser = takeLazyByteString >>= \b -> case readToken B readBotBody b of Nothing -> fail "Invalid bot token" - Just t -> return t + Just t -> pure t instance FromByteString (Token Provider) where parser = takeLazyByteString >>= \b -> case readToken P readProviderBody b of Nothing -> fail "Invalid provider token" - Just t -> return t + Just t -> pure t instance FromByteString (Token LegalHoldAccess) where parser = takeLazyByteString >>= \b -> case readToken LA readLegalHoldAccessBody b of Nothing -> fail "Invalid access token" - Just t -> return t + Just t -> pure t instance FromByteString (Token LegalHoldUser) where parser = takeLazyByteString >>= \b -> case readToken LU readLegalHoldUserBody b of Nothing -> fail "Invalid user token" - Just t -> return t + Just t -> pure t instance ToByteString a => ToByteString (Token a) where builder = writeToken @@ -236,7 +236,7 @@ mkToken :: Signature -> Header -> a -> Token a mkToken = Token mkHeader :: Int -> Int -> Integer -> Type -> Maybe Tag -> Header -mkHeader v k d t g = Header v k d t g +mkHeader = Header mkAccess :: UUID -> Word64 -> Access mkAccess = Access diff --git a/libs/zauth/src/Data/ZAuth/Validation.hs b/libs/zauth/src/Data/ZAuth/Validation.hs index 6bafd2e87ea..97c2a96836e 100644 --- a/libs/zauth/src/Data/ZAuth/Validation.hs +++ b/libs/zauth/src/Data/ZAuth/Validation.hs @@ -104,13 +104,13 @@ validate Nothing Nothing = throwError Invalid validate (Just _) Nothing = throwError Invalid validate Nothing (Just t) = validateAccess t validate (Just c) (Just t) = do - u <- maybe (throwError Invalid) return (fromByteString c) - a <- maybe (throwError Invalid) return (fromByteString t) + u <- maybe (throwError Invalid) pure (fromByteString c) + a <- maybe (throwError Invalid) pure (fromByteString t) void $ check u void $ check a unless (u ^. body . user == a ^. body . userId) $ throwError Invalid - return a + pure a check :: ToByteString a => Token a -> Validate (Token a) check t = do @@ -124,11 +124,11 @@ check t = do throwError Falsified isExpired <- if t ^. header . time == -1 - then return False + then pure False else (t ^. header . time <) <$> now when isExpired $ throwError Expired - return t + pure t now :: (Functor m, MonadIO m) => m Integer now = floor <$> liftIO getPOSIXTime diff --git a/libs/zauth/test/Arbitraries.hs b/libs/zauth/test/Arbitraries.hs index bb17ae9b58d..16d2f9c8d69 100644 --- a/libs/zauth/test/Arbitraries.hs +++ b/libs/zauth/test/Arbitraries.hs @@ -74,7 +74,7 @@ instance Arbitrary LegalHoldUser where arbitrary = mkLegalHoldUser <$> arbitrary <*> arbitrary instance Arbitrary ByteString where - arbitrary = fromString <$> arbitrary `suchThat` (not . any (== '.')) + arbitrary = fromString <$> arbitrary `suchThat` notElem '.' instance Arbitrary Signature where arbitrary = Signature <$> arbitrary @@ -83,7 +83,7 @@ instance Arbitrary Type where arbitrary = elements [A, U, LA, LU] instance Arbitrary Tag where - arbitrary = return S + arbitrary = pure S instance Bounded UUID where minBound = nil diff --git a/libs/zauth/test/ZAuth.hs b/libs/zauth/test/ZAuth.hs index 703cbd69b5a..1b6fd4d518f 100644 --- a/libs/zauth/test/ZAuth.hs +++ b/libs/zauth/test/ZAuth.hs @@ -42,7 +42,7 @@ tests = do (p3, s3) <- newKeyPair z <- C.mkEnv s1 [s2, s3] let v = V.mkEnv p1 [p2, p3] - return $ + pure $ testGroup "ZAuth" [ testGroup @@ -69,10 +69,10 @@ defDuration :: Integer defDuration = 1 testUserIsNotLegalHoldUser :: Token LegalHoldUser -> Bool -testUserIsNotLegalHoldUser t = fromByteString @(Token User) (toByteString' t) == Nothing +testUserIsNotLegalHoldUser t = isNothing (fromByteString @(Token User) (toByteString' t)) testUserIsNotLegalHoldUser' :: Token User -> Bool -testUserIsNotLegalHoldUser' t = fromByteString @(Token LegalHoldUser) (toByteString' t) == Nothing +testUserIsNotLegalHoldUser' t = isNothing (fromByteString @(Token LegalHoldUser) (toByteString' t)) testDecEncAccessToken :: Token Access -> Bool testDecEncAccessToken t = fromByteString (toByteString' t) == Just t @@ -117,8 +117,8 @@ testSignAndVerify p = do testRandDevIds :: Create () testRandDevIds = do u <- liftIO nextRandom - t1 <- (view body) <$> accessToken1 defDuration u - t2 <- (view body) <$> accessToken1 defDuration u + t1 <- view body <$> accessToken1 defDuration u + t2 <- view body <$> accessToken1 defDuration u liftIO $ assertBool "unexpected: Same device ID." (t1 ^. connection /= t2 ^. connection) -- Helpers: